如何在 C 或 C++ 中反转字符串?
c++cserver side programmingprogramming
在本节中,我们将了解如何反转字符串。因此,我们不会使用其他内存空间进行反转。在 C++ 中,我们可以使用 std::string。但对于 C,我们必须使用字符数组。在此程序中,我们使用字符数组来获取字符串。然后反转它。
输入:字符串"This is a 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) ; //获取字符串的长度 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