C language to achieve the combination of strings

Time:2022-5-6

After learning Perl and python, processing strings is just something I like to do. String splicing is an easy thing in these high-level scripting languages.

C language is my entry-level programming language, but I haven’t always understood this language very well. To be exact, I know little about the huge standard library and GNU and other function libraries.

How to use C language to splice strings? Previously, I must define a new “string” and then copy it in memory. In fact, there is a twin brother of printf function that can realize this function, that is sprintf.

In fact, when I came into contact with the operating system, I had a little understanding of this function. That is, this function is lower than printf when implementing screen display, and can directly operate memory. So, how to use this function to splice strings?

The model 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 code is compiled and executed 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

From the above results, we can see that the string splicing function is realized through sprintf.

The above C language merging string is all that Xiaobian has shared with you. I hope it can give you a reference and support developeppaer.