concatenating strings in C

做~自己de王妃 提交于 2019-12-01 08:55:25

I think you need string concatenation:

#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;
}

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

To concatenate more than two strings, you can use sprintf, e.g.

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

Try taking a look at the strcat API. With sufficient buffer space, you can add one string onto the end of another one.

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

Reference page for strcat

'strcat' is the answer, but thought there should be an example that touches on the buffer-size issue explicitly.

#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). Watch your buffer sizes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!