如何在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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短