将字符串数组逆序输出
时间: 2024-06-14 22:06:00 浏览: 12
以下是将字符串数组逆序输出的示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<string> arr = {"abc", "def", "ghi", "jkl"};
reverse(arr.begin(), arr.end());
for (string s : arr) {
cout << s << " ";
}
return 0;
}
```
输出结果为:"jkl ghi def abc"
相关问题
c语言怎么逆序输出一个字符串数组
在C语言中,可以使用循环来逆序输出一个字符串数组。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#define maxn 100
int main() {
char a[maxn];
int i;
gets(a); // 或者使用 scanf("%s",a);
for(i=strlen(a)-1; i>=0; i--) {
printf("%c", a[i]);
}
return 0;
}
```
这段代码首先声明了一个字符数组 `a`,然后使用 `gets(a)` 或者 `scanf("%s",a)` 来输入字符串。接下来,使用循环从字符串的最后一个字符开始,逐个输出字符,直到第一个字符。最后,返回0表示程序正常结束。
4.程序设计:输入一个字符串,逆序输出。 要求: (1)利用字符数组初始化字符串。 (2)将字符串逆序保存到另一个字符数组里输出。
你好,谢谢你使用ChitGPT进行对话!针对你的问题,以下是可以实现该要求的程序代码示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!"; // 初始化字符串
char reversed[strlen(str) + 1]; // 定义保存逆序后字符串的字符数组
int length = strlen(str); // 获取字符串长度
for(int i = 0; i < length; i++) { // 逆序遍历字符串并保存到新的字符数组
reversed[i] = str[length - i - 1];
}
reversed[length] = '\0'; // 往字符数组最后一个位置加上结束符,形成完整的字符串
printf("原字符串:%s\n", str);
printf("逆序后的字符串:%s\n", reversed); // 输出逆序后的字符串
return 0;
}
```
上述代码通过`char`类型的字符数组来保存字符串,并通过`strlen()`函数获取字符串长度,然后使用`for`循环逆序遍历字符串,并把每个字符保存到另一个字符数组中,最后输出逆序后的字符串。
希望可以帮助你解决问题,如果你还有其他疑问,欢迎继续提问!
相关推荐
![](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)