如您所知,在 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
这里,两个字符串
s1 和
s2 连接起来,结果存储在
s1 中。
需要注意的是,
s1 的长度应该足以容纳连接后的字符串。否则,您可能会得到意外的输出。