用C++ 定义一个字符数组s1,并输入一个字符串1,写一段代码,要求把字符串1中的字母拷贝到字符数组s2中并输出。然后再优化代码
时间: 2023-06-02 12:06:13 浏览: 52
可以参考以下代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char s1[MAX_LEN];
char s2[MAX_LEN];
printf("请输入字符串1:\n");
scanf("%s", s1);
// 复制字符串1到字符串2
strcpy(s2, s1);
printf("拷贝后的字符串2为:%s\n", s2);
return 0;
}
```
优化代码可以使用 strncpy() 函数,该函数可以指定拷贝的长度,防止越界访问。
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char s1[MAX_LEN];
char s2[MAX_LEN];
printf("请输入字符串1:\n");
scanf("%s", s1);
// 复制字符串1到字符串2
strncpy(s2, s1, MAX_LEN - 1);
s2[MAX_LEN - 1] = '\0';
printf("拷贝后的字符串2为:%s\n", s2);
return 0;
}
```
相关问题
C++程序中定义了2个字符数组,要求把s1复制给s2,然后输出s2
好的,以下是您要求的小程序,使用 C++ 语言编写:
```cpp
#include <iostream>
#include <cstring>
int main() {
const int max_length = 20; // 定义数组的最大长度
char s1[max_length] = "I am a student."; // 定义字符数组s1并初始化
char s2[max_length]; // 定义字符数组s2
std::strcpy(s2, s1); // 将s1复制给s2
std::cout << s2 << std::endl; // 输出s2
return 0;
}
```
程序中定义了两个字符数组 `s1` 和 `s2`,并设定其最大长度为 `max_length`。首先对 `s1` 进行初始化,然后使用 `std::strcpy()` 函数将 `s1` 复制给 `s2`。最后使用 `std::cout` 输出 `s2` 中的字符串,并添加换行符 `std::endl`。最终输出结果为:
```
I am a student.
```
给定一个字符串 s1 , 字符串的长度不超过 500500 , 请将所有大写字母改成小写字母 使用c++代码实现
可以使用 C++ 标准库中的 `std::transform` 函数来实现:
```cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s1 = "Hello, World!";
std::transform(s1.begin(), s1.end(), s1.begin(), [](unsigned char c) {
return std::tolower(c);
});
std::cout << s1 << '\n';
return 0;
}
```
输出:
```
hello, world!
```