21xrx.com
2024-09-19 10:04:37 Thursday
登录
文章检索 我的文章 写文章
C语言中字符串合并的方法及示例
2023-06-14 23:03:07 深夜i     --     --
C语言 字符串 合并 strcat() sprintf()

在C语言程序中,对于字符串(即字符型数组)的操作是至关重要的。有时候我们需要将两个字符串合并成一个字符串,方便后续处理。本文将介绍C语言中字符串合并的方法及示例。

方法一:使用strcat()函数

strcat()函数可将第二个参数指向的字符串添加到第一个参数指向的字符串末尾,从而实现字符串合并。具体语法如下:


char* strcat(char* destination, const char* source);

其中,destination参数是指向目标字符串的指针,source参数是指向源字符串的指针。下面是一个示例代码:


#include

#include

int main() {

  char s1[50] = "Hello";

  char s2[20] = "world!";

  

  strcat(s1, s2);

  

  printf("字符串合并结果:%s", s1);

  

  return 0;

}

执行结果为:


字符串合并结果:Helloworld!

方法二:使用sprintf()函数

sprintf()函数可实现将多个字符串合并成一个字符串。具体语法如下:


int sprintf(char* str, const char* format, ...);

其中,str参数是指向存储结果字符串的位置的指针,format参数是包含多个格式说明符的字符串,...代表参数列表。下面是一个示例代码:


#include

#include

int main() {

  char s1[50] = "Hello";

  char s2[20] = "world!";

  char result[70];

  

  sprintf(result, "%s%s", s1, s2);

  

  printf("字符串合并结果:%s", result);

  

  return 0;

}

执行结果为:


字符串合并结果:Helloworld!

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章