字符串反转

这曾经是我的一个面试题,给定一字符串,将每个单词的字符顺序倒置,单词间的顺序不变。例如:输入字符串“I love you”,输出“I evol uoy”。

复制代码
#include <iostream>
#include <sstream>
using namespace std;

//计算并返回字符串长度
int Length(char *str)
{
int length=0;
while((*str++)!='')
length++;
return length;
}

//对单个单词字符反转
void _Reverse(char *str,int low,int high)
{
char tempChar;
while(low<high)
{
tempChar=str[low];
str[low]=str[high];
str[high]=tempChar;
low++;
high--;
}
}

//利用字符串流读取每个单词并将其反转,单词间有多个空格时合并为一个
void Reverse(char *str)
{
istringstream in(str);
int length;
for(string s;in>>s;)
{
length=Length(&s[0]);
_Reverse(&s[0],0,length-1);
cout<<s<<" ";
}
}

//反转的另一个方法,直接对原字符串操作
void ReverseVer2(char *str)
{
int low,high;
int length=Length(str);
for(int i=0;i<=length;i++)
{
if(i==0&&str[i]!='40')
{
low=i;
continue;
}
if(str[i]!='40'&&str[i-1]=='40')
{
low=i;
continue;
}
if(str[i]=='40'||str[i]=='')
{
high=i-1;
_Reverse(str,low,high);
}
}
}

int main()
{
char str[]="I love you";
cout<<"first method:";
Reverse(str);
cout<<endl;
ReverseVer2(str);
cout<<"second method:"<<str<<endl;
return 0;
}
复制代码

运行结果截图:

如果一件事情你觉得难的完不成,你可以把它分为若干步,并不断寻找合适的方法。最后你发现你会是个超人。不要给自己找麻烦,但遇到麻烦绝不怕,更不要退缩。 电工查找电路不通点的最快方法是:分段诊断排除,快速定位。你有什么启示吗? 求知若饥,虚心若愚。 当你对一个事情掌控不足的时候,你需要做的就是“梳理”,并制定相应的规章制度,并使资源各司其职。
原文地址:https://www.cnblogs.com/wvqusrtg/p/4498258.html