The C language implements merging strings

  • 2020-06-23 01:30:04
  • OfStack

After learning Perl and Python, dealing with strings is just one of my favorite things to do. String concatenation is a breeze in these high-level scripting languages.

C is my introductory programming language, but I don't know much about it. Specifically, I know very little about the vast standard library and function libraries like GNU.

How to use C for string concatenation? Previously, I must have defined a new "string" and copied it into memory. In fact, there is a twin of the printf function that can do this: sprintf.

In fact, I know a little bit about this function when I touch the operating system. This function is much lower level than printf when it comes to screen, and can manipulate memory directly. So, how do you use this function for string concatenation?

The demonstration code is as follows:


#include"stdio.h"

#include"stdlib.h"

#include"string.h"

 

int main(void)

{

  char str1[] = "my string 1";

  char str2[] = "string 2";

  char *strCat = (char*)malloc(strlen(str1) + strlen(str2));

 

  sprintf(strCat,"%s%s",str1,str2);

 

  printf("%s\n",strCat);

 

  return 0;

}

The compilation of the code is performed as follows:

E:\01_workSpace\02_programme_language\01_clang\2017\08\08 > gccstrCat.c

E:\01_workSpace\02_programme_language\01_clang\2017\08\08 > a

my string 1string2

As you can see from the above results, string concatenation is implemented through sprintf.


Related articles: