现在的位置: 首页 > 综合 > 正文

句子翻转的STL实现

2018年05月13日 ⁄ 综合 ⁄ 共 699字 ⁄ 字号 评论关闭
字符串翻转的例子
输入如 A fox has jumped into the river
输出为 river the into jumped has fox A








#include <algorithm>
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <iostream>
using namespace std;

bool reverseSentence( const char *input, vector<string> &output)
{
    int len = strlen(input);
    string word;
    for ( int i = 0; i < len ; i ++ )
    {
        char currentChar = *(input+i);
        if ( ' ' == currentChar || '\0' == currentChar )
        {
            if ( word != "" )
            {
                output.push_back(word);
                word = "";
                continue;
            }
        }
        else
        {
            word += currentChar;
        }
    }
    if ( word != "")
    {
       output.push_back(word);
    }
    reverse(output.begin(),output.end());
    return true;
}


int main()
{
    vector<string> result;
    string str= "A fox has jumped into the river";
    reverseSentence( str.c_str(),result);
    for ( int i = 0 ; i < result.size(); i ++ )
    {
        cout << result[i]<<endl;
    }
    return 0;
}

抱歉!评论已关闭.