string反转字符串c++
时间: 2023-03-25 08:02:20 浏览: 80
可以使用一个循环,从字符串末尾开始遍历,将每个字符依次添加到一个新的字符串中,最终得到反转后的字符串。具体代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100], rev[100];
int i, j;
printf("请输入一个字符串:");
scanf("%s", str);
j = ;
for (i = strlen(str) - 1; i >= ; i--) {
rev[j++] = str[i];
}
rev[j] = '\';
printf("反转后的字符串为:%s\n", rev);
return ;
}
```
相关问题
leetcode反转字符串c++
要反转一个字符串,可以使用双指针的方法。具体实现如下:
```cpp
#include <algorithm>
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
// 交换左右指针所指向的字符
swap(s[left], s[right]);
left++;
right--;
}
}
```
上述代码中,我们使用两个指针 `left` 和 `right` 分别指向字符串的首尾元素。然后,我们不断交换 `left` 和 `right` 指针所指向的字符,并将 `left` 向右移动、`right` 向左移动。直到 `left` 不再小于 `right`,反转完成。
注意,我们传入的字符串 `s` 是一个引用,这样在函数内部修改 `s` 的内容会反映到函数外部。
希望能解答到您的问题!如有更多疑问,请继续提问。
string字符串反转函数c++
有三种常用的方法可以对字符串进行反转。第一种是使用string.h中的strrev函数,第二种是使用algorithm中的reverse函数,第三种是自己编写反转函数。其中,第一种方法只适用于字符数组,而后两种方法可以处理string类型的字符串。以下是三种方法的代码示例:
第一种:使用string.h中的strrev函数
```
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[] = "hello";
strrev(s);
cout << s << endl;
return 0;
}
```
第二种:使用algorithm中的reverse函数
```
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(s.begin(), s.end());
cout << s << endl;
return 0;
}
```
第三种:自己编写反转函数
```
#include <iostream>
using namespace std;
void Reverse(char *s, int n) {
for(int i = 0, j = n - 1; i < j; i++, j--) {
char c = s[i];
s[i] = s[j];
s[j] = c;
}
}
int main() {
char s[] = "hello";
Reverse(s, 5);
cout << s << endl;
return 0;
}
```