<分区>
我刚刚开始学习 C++。我正在编写一个程序来反转字符串中单词的顺序。如果有一句话,“我爱纽约!”。应该改为,“!York New love I”。
我使用的算法有两个简单的步骤。
- 反转字符串。
- 颠倒单词的字母。
例如,对于上面的字符串,我会先将其转换为“!kroY weN evol I”,然后我会将“!kroY”等单词的字母更改为“York!”。
现在的问题是,我怎么知道这个词从哪里开始,从哪里结束。这是我到目前为止所做的。但是这个程序没有按预期工作。我无法识别这个词然后将其反转。
#include <iostream>
#include <string>
std::string reverseText(std::string x){
std::string y;
for(int i=x.size()-1;i>=0;i--) y += x[i];
return y;
}
std::string reverseWords(std::string x){
std::string y = reverseText(x);
bool wordFound = true;
std::string temp1,ans;
for(size_t i=0;i<y.size();i++){
if(wordFound){
if(y[i]!=' ') temp1+=y[i]; // if there is a letter, store that in temp1.
else if(y[i]==' ') // if there is a space, that means word has ended.
{
ans += reverseText(temp1); // store that word, in ans.
temp1=" ";
wordFound=false;}
}
if(y[i]==' ' && y[i+1]!=' ') wordFound=true;
}
return ans;
}
int main(){
std::cout<<reverseWords("My name is Michael");
}
输出:米氏名