在C中连接字符串

我想知道是否有办法为字符串添加值,而不是像1 + 1 = 2但像1 + 1 = 11。

我认为你需要字符串连接:

#include  #include  int main() { char str1[50] = "Hello "; char str2[] = "World"; strcat(str1, str2); printf("str1: %s\n", str1); return 0; } 

来自: http : //irc.essex.ac.uk/www.iota-six.co.uk/c/g6_strcat_strncat.asp

要连接两个以上的字符串,可以使用sprintf,例如

 char buffer[101]; sprintf(buffer, "%s%s%s%s", "this", " is", " my", " story"); 

试试看看strcat API。 有足够的缓冲区空间,您可以在另一个字符串的末尾添加一个字符串。

 char[50] buffer; strcpy(buffer, "1"); printf("%s\n", buffer); // prints 1 strcat(buffer, "1"); printf("%s\n", buffer); // prints 11 

strcat的参考页面

‘strcat’就是答案,但我认为应该有一个明确涉及缓冲区大小问题的例子。

 #include  #include  /* str1 and str2 are the strings that you want to concatenate... */ /* result buffer needs to be one larger than the combined length */ /* of the two strings */ char *result = malloc((strlen(str1) + strlen(str2) + 1)); strcpy(result, str1); strcat(result, str2); 

strcat(s1,s2)。 观察缓冲区大小。