如何在C语言中连接字符串,不像1
+1
=2
,而是像1
+1
=11
。
如何在C语言中连接字符串,不像1
+1
=2
,而是像1
+1
=11
。
我认为你需要字符串拼接:
#include <stdio.h>
#include <string.h>
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
strcat()和strncat()函数用于将一个字符串连接到另一个字符串的末尾。
strcat()函数将源字符串的内容复制到目标字符串的末尾,并在目标字符串中添加一个空字符,以终止字符串。
strncat()函数与strcat()函数类似,但是它只将源字符串的前n个字符复制到目标字符串的末尾(不包括源字符串的空字符),并在目标字符串中添加一个空字符,以终止字符串。
这两个函数都需要确保目标字符串具有足够的空间来容纳源字符串,否则可能会导致缓冲区溢出错误。
要连接两个以上的字符串,你可以使用sprintf函数,例如:
char buffer[101];
sprintf(buffer, "%s%s%s%s", "this", " is", " my", " story");
#include <string.h>
#include <stdlib.h>
/* 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);
result
,导致内存泄漏,并且至少需要使用一个strcpy()。此外,它扩展了str1,但暗示您希望str1和str2都是只读的。 - RBerteig尝试查看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(s1, s2)。注意你的缓冲区大小。