如您所知,在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的长度应足以容纳连接后的字符串。如果不足,您可能会得到意外的输出。