编写程序实现在数组中的字符串逆序存放
时间: 2024-05-15 14:14:39 浏览: 82
可以使用双指针来逆序存放数组中的字符串。具体方法是:让一个指针指向数组的第一个元素,让另一个指针指向数组的最后一个元素,然后不断交换它们所指向的元素,直到两个指针相遇。以下是示例代码:
```
#include <iostream>
#include <string>
using namespace std;
void reverseStringArray(string arr[], int size)
{
int start = 0;
int end = size - 1;
while (start < end)
{
swap(arr[start], arr[end]);
start++;
end--;
}
}
int main()
{
string arr[] = { "hello", "world", "from", "AI" };
int size = sizeof(arr) / sizeof(string);
reverseStringArray(arr, size);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:"AI from world hello"。
相关问题
c语言编写一个函数 Inverse0,实现将字符数组中的字符串逆序存放的功能。用数组a存放逆序存放前的数组元素,用数组b存放逆序存放后的数组元素。
好的,以下是C语言实现的代码:
```c
void Inverse0(char* str) {
char a[1000], b[1000];
int len = strlen(str);
for (int i = 0; i < len; i++) {
a[i] = str[i];
}
for (int i = 0; i < len; i++) {
b[i] = a[len - i - 1];
}
for (int i = 0; i < len; i++) {
str[i] = b[i];
}
}
```
以上代码中,我们先将原始字符串按照顺序存储到数组a中,然后再将数组a中的元素按照相反的顺序存储到数组b中,最后再将数组b中的元素按照顺序存储回原始字符串中,即可实现字符串逆序存放的功能。
请注意,由于我们使用了数组a和数组b,因此需要定义一个足够大的数组来存储字符串,以上代码中我们定义了大小为1000的数组。如果您的字符串比较长,可能需要调整数组的大小。
编写一个西数 Inverse0,实现将字符数组中的字符串逆序存放的功能。 提示:有两种方法。 (1用数组a存放逆序存放前的数组元素,用数组b存放逆序存放后的数组元素。
好的,我的回答如下:
方法一:
```c
void Inverse0(char* str) {
int len = strlen(str);
char temp;
for (int i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
```
方法二:
```c
void Inverse0(char* str) {
char a[1000], b[1000];
int len = strlen(str);
for (int i = 0; i < len; i++) {
a[i] = str[i];
}
for (int i = 0; i < len; i++) {
b[i] = a[len - i - 1];
}
for (int i = 0; i < len; i++) {
str[i] = b[i];
}
}
```
以上是两种实现方法,您可以根据实际情况选择其中一种进行使用。
阅读全文
相关推荐
![](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)