输入字符串s1,s2,将字符串s2复制到s1中(strcpy( ) 函数)
时间: 2024-05-11 11:16:38 浏览: 12
好的,这是一个关于字符串操作的问题。要使用 strcpy() 函数将字符串 s2 复制到字符串 s1 中,可以这样写代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char s1[100], s2[50];
printf("请输入字符串 s2:\n");
scanf("%s", s2);
strcpy(s1, s2);
printf("复制后的字符串 s1 为:%s\n", s1);
return 0;
}
```
在这段代码中,我们首先声明了两个字符数组 s1 和 s2。然后,使用 scanf() 函数读入字符串 s2。最后,使用 strcpy() 函数将字符串 s2 复制到 s1 中,并输出复制后的结果。需要注意的是,strcpy() 函数需要包含头文件 string.h。
相关问题
写一个子函数实现strcpy功能,将字符串s1复制到s2
下面是一个实现strcpy功能的子函数,可以将字符串s1复制到s2中:
```c
void my_strcpy(char *s2, const char *s1)
{
while (*s1 != '\0') {
*s2 = *s1;
s1++;
s2++;
}
*s2 = '\0';
}
```
这个函数的思路比较简单,就是从源字符串s1的第一个字符开始,逐个复制到目标字符串s2中,直到遇到字符串结束符'\0'为止。需要注意的是,在这个过程中,源字符串s1是不能被修改的,因此需要用const关键字来修饰它。
在c++中,将字符串s1复制为s2
在 C++ 中,可以使用 `strcpy()` 函数将字符串 `s1` 复制到另一个字符串 `s2` 中。示例代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s1[] = "Hello, world!";
char s2[100];
// 将 s1 复制到 s2 中
strcpy(s2, s1);
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
return 0;
}
```
运行结果:
```
s1: Hello, world!
s2: Hello, world!
```
需要注意的是,`strcpy()` 函数会复制整个字符串,包括字符串末尾的空字符。因此,目标字符串 `s2` 必须足够大,以容纳源字符串 `s1` 的内容和空字符。在上面的代码中,我定义了一个大小为 100 的字符数组 `s2`,以确保能够容纳 `s1` 的内容。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)