定义新的函数将两个字符串连接起来,不要用strcat函数。修改该程序,要求将红色部分用一个函数来实现。
时间: 2023-06-13 22:02:52 浏览: 53
以下是一个示例程序,其中定义了一个 `mystrcat` 函数来将两个字符串连接起来:
```c
#include <stdio.h>
void mystrcat(char dest[], char src[]) {
int i, j;
i = j = 0;
while (dest[i] != '\0') {
i++;
}
while ((dest[i] = src[j]) != '\0') {
i++;
j++;
}
}
int main() {
char str1[50] = "Hello, ";
char str2[] = "world!";
mystrcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
其中 `mystrcat` 函数的实现如下:
- 首先,在 `dest` 字符串中找到空字符的位置,即字符串的末尾。
- 然后,将 `src` 字符串中的每个字符一个一个地复制到 `dest` 字符串的末尾,直到 `src` 字符串的末尾。
在主函数中,我们先定义了两个字符串 `str1` 和 `str2`,并初始化了 `str1`。然后调用 `mystrcat` 函数将 `str2` 连接到 `str1` 的末尾。最后,输出连接后的字符串 `str1`。
注意,在将 `src` 字符串中的字符复制到 `dest` 字符串的末尾时,我们使用了一个 while 循环和两个指针 `i` 和 `j`。指针 `i` 指向 `dest` 字符串的末尾,指针 `j` 指向 `src` 字符串的开头。每次循环,我们将 `src[j]` 复制到 `dest[i]`,然后递增 `i` 和 `j`,直到 `src` 字符串的末尾。注意,在复制过程中,我们使用了逗号表达式 `(dest[i] = src[j])`,这个表达式将 `src[j]` 赋值给 `dest[i]`,并返回 `dest[i]`。这样,我们可以一边赋值一边递增指针的值。