把输入的字符串中的内容逆置,并保存到新字符串,并输出新字符串
时间: 2023-08-21 10:05:43 浏览: 136
好的,以下是 C++ 代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string input_str, new_str;
// 读取输入字符串
cout << "请输入一个字符串:";
getline(cin, input_str);
// 逆置字符串并保存到新字符串
for (int i = input_str.length() - 1; i >= 0; i--) {
new_str += input_str[i];
}
// 输出新字符串
cout << "逆置后的字符串为:" << new_str << endl;
return 0;
}
```
该程序会先要求用户输入一个字符串,然后将其中的内容逆置,保存到新字符串中,并最终输出新字符串。使用 `getline()` 函数可以读取一行字符串,使用 `string` 类型变量可以方便地进行字符串拼接。
相关问题
17. 把从键盘输入的字符串逆置存放并输出
好的,可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf("逆置后的字符串为:%s\n", str);
return 0;
}
```
运行程序后,输入一个字符串,程序将会把字符串逆置并输出。
用c语言编写一个函数把字符串中内容逆置
以下是使用 C 语言编写的函数,将输入字符串逆置:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
int main() {
char str[] = "hello world";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
该代码中,`reverseString` 函数接收一个字符数组 `str`,并使用循环将字符串中的内容逆置。`main` 函数中定义了一个字符串 `str`,并输出原字符串及逆置后的字符串。
相关推荐
![c](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)