Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Joining Strings

You often need to put a text together from pieces: a first name and a last name, a greeting and a name. The function strcat (string concatenate, which means join) from string.h adds a text to the end of the text that's already in an array:

char full_name[30] = "Anna";
strcat(full_name, " ");
strcat(full_name, "Smith");
printf("%s\n", full_name);

This prints:

Anna Smith

strcat finds the '\0' at the end of full_name and copies the new text there, including its own '\0'. The order is the same as with strcpy: first the array that changes, then the text to add. The second text stays as it was.

A common way to start is with an empty string, "", which holds only the '\0', and to add the pieces one by one. That comes in handy in a loop:

char stars[10] = "";
for (int i = 0; i < 3; i++) {
    strcat(stars, "*");
    printf("%s\n", stars);
}

This prints:

*
**
***

The array must have room for everything: the text that's already in it, the new text and one '\0'. "Anna Smith" needs 4 + 1 + 5 + 1 = 11 elements, so full_name[30] is more than enough. As with strcpy, the program doesn't compile here when Clang can see that the new text won't fit:

char greeting[8] = "Hello";
strcat(greeting, ", world!");
main.c:6:5: error: 'strcat' will always overflow; destination buffer has size 8, but the source string has length 9 (including NUL byte) [-Werror,-Wfortify-source]

Clang only checks the new text, though. When the array is already partly full, it often doesn't see the problem, and strcat writes past the end of the array without a word. So count how much room you need before joining, and when you aren't sure, make the array bigger.

Instructions

  1. 1

    Before the last printf, join first_name, a space and last_name into full_name, using strcat three times. The output should be Name: Tom Baker.

  2. 2

    Below that, create char laugh[20] = ""; and, in a for loop that runs 4 times, add "ha" to it. After the loop, print it: hahahaha.

Back

6/10

  1. 1. Text in a Variable
  2. 2. Characters of a String
  3. 3. Length of a String
  4. 4. Going Through a String
  5. 5. Room in the Array
  6. 6. Joining Strings
  7. 7. Comparing Strings
  8. 8. Character Functions
  9. 9. Aligned Columns
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.