4

如何在 C 中连接字符串,不像1+ 1=2而是像1+ 1= 11

4

5 回答 5

9

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

#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

于 2009-06-09T05:41:10.943 回答
6

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

char buffer[101];
sprintf(buffer, "%s%s%s%s", "this", " is", " my", " story");
于 2009-06-09T05:52:51.650 回答
1

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

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

strcat 的参考页

于 2009-06-09T05:39:24.050 回答
1

'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);
于 2009-06-09T05:54:16.593 回答
0

strcat(s1, s2)。注意你的缓冲区大小。

于 2009-06-09T05:39:16.390 回答