C语言连接两个字符串的程序

要理解这个示例,您应该了解以下 C 编程 主题


如您所知,在C编程中连接两个字符串的最佳方法是使用strcat()函数。然而,在本例中,我们将手动连接两个字符串。


不使用strcat()连接两个字符串

#include <stdio.h>
int main() {
  char s1[100] = "programming ", s2[] = "is awesome";
  int length, j;

  // store length of s1 in the length variable
  length = 0;
  while (s1[length] != '\0') {
    ++length;
  }

  // concatenate s2 to s1
  for (j = 0; s2[j] != '\0'; ++j, ++length) {
    s1[length] = s2[j];
  }

  // terminating the s1 string
  s1[length] = '\0';

  printf("After concatenation: ");
  puts(s1);

  return 0;
}

输出

After concatenation: programming is awesome

在这里,两个字符串s1s2被连接起来,结果存储在s1中。

需要注意的是,s1的长度应足以容纳连接后的字符串。如果不足,您可能会得到意外的输出。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战