如何在 C 或 C++ 中就地反转一个字符串?
在本文中,我们将了解如何就地反转一个字符串。因此,我们不会使用其他内存空间进行反转。在 C++ 中,我们可以使用 std::string。但对于 C,我们必须使用字符数组。在本程序中,我们使用字符数组获取字符串。然后进行反转。
Input: A string “This is a string” Output: The reversed string “gnirts a si sihT”
算法
reverse_string(str)
输入 − 字符串
输出 − 反转后的字符串。
len := the length of the string i := 0 and j := (len-1) while i < j, do swap the characters from position i and j i := i + 1 j := j - 1 done
示例代码
#include <iostream>
#include<cstring>
using namespace std;
void reverse(char s[]) {
int len = strlen(s) ; //get the length of the string
int i, j;
for (i = 0, j = len - 1; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
int main() {
char s[20] = "This is a string";
cout << "Main String: " << s <<endl;
reverse(s);
cout << "Reversed String: " << s <<endl;
}输出
Main String: This is a string Reversed String: gnirts a si sihT
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP