c++ - 反转字符串中的单词c++

标签 c++ string algorithm

<分区>

我刚刚开始学习 C++。我正在编写一个程序来反转字符串中单词的顺序。如果有一句话,“我爱纽约!”。应该改为,“!York New love I”。

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

  1. 反转字符串。
  2. 颠倒单词的字母。

例如,对于上面的字符串,我会先将其转换为“!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");
}

输出:米氏名

最佳答案

我没有对此进行过广泛的测试,它仍然可能存在问题,但它为您提供的案例生成了正确的输出。我试图在不改变太多的情况下修复你的代码。

#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);

关于c++ - 反转字符串中的单词c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24850313/

相关文章:

c++ - 我的逻辑让我失望(C++、nslookup、字符比较)

linux - 从 bash 中的字符串中提取数字

algorithm - Matlab FFT 和 Fortran Rosetta 代码 FFT 的差异

python - 为什么我不能在 pandas 函数中应用 shift?

java - 生命游戏振荡器和宇宙飞船不工作

c++ - 如何将ios设备联系人与qt app同步?

c++ - 将参数传递给 "array-like"容器构造函数

c++ - 清理 C++ STL 指针列表时出现双重 dealloc 问题

c++ - 如何解析多行的字符串对?

PHP: strpos() 找不到 '“'