3、编写stringcopy(char *str1,char *str2)子函数实现str2到str1的字符串拷贝。主函数中定义char s1[20]; char s2[]=“Hello World!”, 并通过stringcopy函数调用,将s2中的字符串复制到s1。
时间: 2024-03-21 11:38:17 浏览: 79
好的,以下是实现字符串拷贝的 `stringcopy` 函数:
```c++
#include <iostream>
using namespace std;
void stringcopy(char *str1, char *str2)
{
while(*str2 != '\0')
{
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
int main()
{
char s1[20];
char s2[] = "Hello World!";
stringcopy(s1, s2);
cout << "s1 = " << s1 << endl;
return 0;
}
```
运行结果如下:
```
s1 = Hello World!
```
解释一下代码:
我们定义了一个 `stringcopy` 函数,它接收两个参数:一个指向字符数组的指针 `str1` 和一个指向字符数组的指针 `str2`。在函数内部,我们使用一个循环遍历字符串 `str2` 中的每个字符,并将它们逐个复制到字符串 `str1` 中,直到遇到字符串末尾的空字符 `\0`。最后,我们在字符串 `str1` 的末尾添加一个空字符 `\0`,以表示字符串的结束。
在主函数中,我们定义了两个字符数组 `s1` 和 `s2`,其中 `s2` 包含了要复制的字符串。然后,我们调用 `stringcopy` 函数并传递 `s1` 和 `s2` 作为参数,将 `s2` 中的字符串复制到 `s1` 中。最后,我们输出 `s1` 的值,以验证字符串复制是否成功。
阅读全文
相关推荐
















