【发布时间】:2014-07-20 12:04:56
【问题描述】:
我刚刚开始学习 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");
}
输出:Michaelis 名字
【问题讨论】:
-
什么不起作用?运行时会发生什么?
-
@Theolodis 输出不正确,我的逻辑不对。我猜。
-
好吧,将你得到的输出添加到问题中会很好;)
-
@Theolodis 谢谢,我已经添加了输出。
-
该问题现已作为重复项关闭,但其他问题中的所有答案都是错误的。 Here 是我的。