简体   繁体   中英

Using strcat() function in C

While concatenating C with A the result is not what I wanted. How can I get hellojames instead of helloworldjames ?

char  A[12] =  "hello";
char  B[12] =  "world";
char  C[12] =  "james";

strcat(A,B);
printf("%s", A);
output = helloworld


strcat(A,C);
printf("%s",A);
output = helloworldjames

When you use strcat(A, B), the null char ('\\0') marking the end of the A string gets replaced by the first char in B and all the following chars in B get appended from this point onward to A (that must be large enough to hold the result of the concatenation or undefined behaviour could occur).

After the strcat() call, A is no longer what you initially defined it to be, but a new string resulting from the concatenation.

If you want to reverse this, a simple solution is to keep A's lenght before doing the concatenation using strlen() :

int A_len = strlen(A);

This way to reverse strcat(A, B) you only need to set the null char where it used to be before the concatenation:

A[A_len] = '\0';

After this replacement, strcat(A, C) returns hellojames.

When you do the strcat(A,B), you are modifying the string A points to. You need to create a working buffer. Something like:

char work[12];
strcpy(work, A);
strcat(work, B);
printf("%s", work);
strcpy(work, A);
strcat(work, C);
printf("%s", work);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM