不用strcat函数实现字符串的连接
时间: 2023-12-21 07:06:13 浏览: 48
以下是两种不使用strcat函数实现字符串连接的方法:
方法一:使用指针
```c
#include <stdio.h>
void str_concat(char *s1, char *s2) {
while (*s1) { // 找到s1的结尾
s1++;
}
while (*s2) { // 将s2的字符逐个复制到s1的结尾
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0'; // 在s1的结尾添加'\0'
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
str_concat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
```
方法二:使用数组下标
```c
#include <stdio.h>
void str_concat(char s1[], char s2[]) {
int i = 0, j = 0;
while (s1[i] != '\0') { // 找到s1的结尾
i++;
}
while (s2[j] != '\0') { // 将s2的字符逐个复制到s1的结尾
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0'; // 在s1的结尾添加'\0'
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
str_concat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
```