[英]Concatenating strings in C
如何在 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
要连接两个以上的字符串,您可以使用 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 <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);
strcat(s1, s2)。 注意你的缓冲区大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.