c++字符串反转函数
时间: 2023-12-16 18:02:49 浏览: 54
你可以使用下面的代码来实现C语言中的字符串反转函数:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
int i = 0;
int j = strlen(str) - 1;
char temp;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
reverseString(str);
printf("反转后的字符串:%s\n", str);
return 0;
}
```
这段代码定义了一个 `reverseString` 函数,它使用双指针法将字符串进行反转。在 `main` 函数中,我们输入一个字符串并调用 `reverseString` 函数进行反转,然后输出结果。请注意,这里假设输入的字符串长度不超过 100。
相关问题
C++中字符串反转函数
在C++中,可以使用以下方法实现字符串反转函数:
```cpp
#include <iostream>
#include <string>
std::string reverseString(const std::string& str) {
std::string reversedStr;
for (int i = str.length() - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
int main() {
std::string str = "Hello, World!";
std::string reversedStr = reverseString(str);
std::cout << "Reversed String: " << reversedStr << std::endl;
return 0;
}
```
这个函数接受一个 `std::string` 类型的参数,并返回一个反转后的字符串。它使用一个循环从字符串的最后一个字符开始,逐个字符地将其添加到新的字符串中,以实现反转。在上面的示例中,我们将字符串 "Hello, World!" 反转并打印出来。输出将是 "dlroW ,olleH"。
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;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)