为什么我的字符串不完整

时间:2020-09-08 17:52:34

标签: c++ string stl

对于这样的字符串输入-“ i.like.this.program.very.much”,输出应为“ much.very.program.this.like.i”。

这是我的代码-

void func(string s,int n){
    vector<string>v;
    string temp="";
          for(int j=0;j<n;j++){
            if(s[j]!='.'){
                temp+=s[j];
            }
            else{
                v.push_back(temp);
                temp="";
            }
        }
    reverse(v.begin(),v.end());
    for(int i=0;i<v.size();i++){
        cout<<v[i]<<".";
    }
    cout<<"\n";   
}

这里'n'是字符串长度,'s'是字符串。我得到的输出为-“ very.program.this.like.i。”

3 个答案:

答案 0 :(得分:3)

else块仅在遇到句点时执行。由于字符串的末尾没有句号,所以它永远不会压低最后一个单词。

void func(string s, int n) {
    vector<string>v;
    string temp = "";
    for (int j = 0; j < n; j++) {
        if (s[j] != '.') {
            temp += s[j];
        }
        else {
            v.push_back(temp);
            temp = "";
        }
    }
    // v.push_back(temp); This will push the last word / letters
    
    reverse(v.begin(), v.end());
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << ".";
    }
    cout << "\n";
}

答案 1 :(得分:0)

void func(string s,int n){
    vector<string>v;
    string temp="";
          for(int j=0;j<n;j++){
            if(s[j]!='.' || j==0){
                temp+=s[j];
            }
            else{
                v.push_back(temp);
                temp="";
            }
        }
    reverse(v.begin(),v.end());
    for(int i=0;i<v.size();i++){
        cout<<v[i]<<".";
    }
    cout<<"\n";   
}

代码中的语句仅在当前索引字符为句点时才追加字符。

答案 2 :(得分:0)

对于初学者来说,第一个参数应该是对std::string类型的对象的恒定引用。

void func( const string &s, int n);

但是,如果编译器支持C ++ 17标准,则第一个参数最好是std::string_view类型。

第二个参数是多余的。

该函数应返回反向字符串。

您可以使用字符串流来代替循环,

在循环中,最后一个符号'.'之后的子字符串未附加到向量中。

最好使用容器std :: forward_list代替向量,因为您无需反转其元素。

我可以建议以下函数定义,如下面的演示程序所示。

#include <iostream>
#include <string>
#include <forward_list>
#include <iterator>
#include <sstream>

std::string reverse( const std::string &s, char c = '.' )
{
    std::istringstream is( s );
    std::forward_list<std::string> list;
    
    std::string word;
    
    while ( getline( is, word, c ) ) list.push_front( word );
    
    bool first = true;
    std::string result;
    result.reserve( s.size() );     

    for ( const auto &item : list )
    {
        if ( !first ) result += c;
        else first = false;
        result += item;
    }
    
    return result;
}

int main() 
{
    std::string s(  "i.like.this.program.very.much" );
    
    std::cout << reverse( s ) << '\n';
    
    return 0;
}

程序输出为

much.very.program.this.like.i