连接两个字符串的 C 程序
在此示例中,您将学习在不使用 strcat()
函数的情况下手动连接两个字符串。
要理解此示例,您应该具备以下 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
在这里,两个字符串 s1
和 s2
并连接起来,结果存储在 s1
.
需要注意的是,s1
的长度应该足以在保存连接后的字符串。否则,您可能会得到意外的输出。