字符串中的反向单词

Reverse words in a string c++

本文关键字:单词 字符串      更新时间:2023-10-16

我刚刚开始学习c++。我正在写一个程序来反转字符串中的单词顺序。如果有一句话,"我爱纽约!"应该改成"!"纽约新爱我"。

我使用的算法有两个简单的步骤。

  1. 将单词的字母倒序。

例如,对于上面的字符串,我将首先将其转换为,"!当我进化成"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 name

我还没有对它进行广泛的测试,它仍然可能存在问题,但是它为您给出的情况产生了正确的输出。我试着在不改变太多的情况下修复你的代码。

#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;
    }
    ans += reverseText(temp1);
    return ans;
}
int main(){
    std::cout<<reverseWords("My name is Michael");
}

变更汇总

忘记用空格

初始化第一个字符串
std::string temp1 = " ", ans;

在循环y之后,您忘记将temp1的内容"刷新"到answer

ans += reverseText(temp1);