【问题标题】:Spliting string into seperate variables in c++在c ++中将字符串拆分为单独的变量
【发布时间】:2017-08-19 14:55:00
【问题描述】:
vector<string> Util::split(string str, char delimiter){
  vector<string> internal;
  stringstream ss(str); // Turn the string into a stream.
  string tok;

  while(getline(ss, tok, delimiter)) {
    internal.push_back(tok);
  }

return internal;
}

字符串 str = "k 1 1";

getline(ss, tok, ' ')

如果我尝试检查返回向量的大小,它的大小为 ONE。

字符串 str = "k,1,1";

getline(ss, tok, ',')

但是,如果我将分隔符更改为逗号并修改字符串变量 tok。

大小将是三

所以空格有问题

我能做些什么来完成这项工作?我几乎整天都在做这个。

  int main(){

    Util src;
    int runProgram = 1;
    string input;

    while(runProgram!=0){
        cout << "Input your command to perfrom operation: " << endl;
        cin >> input; // user inputs "k 1 1"

       vector<string>sep=src.split(input, ' ');
       cout << sep.size() << endl; // size is one when it should be 3

    }
 }

【问题讨论】:

  • 无论将什么放入tok,显示的代码都将不起作用,因为stringstream 是由另一个名为str 的神秘变量构造的。根据描述,在我看来,显示的代码不是真实代码,而是幻想代码。真正问题的真正答案需要真正的代码,而不是幻想代码。
  • 你是对的,我的错误
  • 您的代码现在显示为works perfectly fine。请提供实际存在问题的minimal reproducible example
  • 我试过了,它正在使用空格分隔符。我使用编译器clang C++11。

标签: c++ vector whitespace delimiter getline


【解决方案1】:
#include <iostream>
using namespace std;

int delimiter(string & str,char ch){
    unsigned int count=1,size=str.size();
    if(size==0){
            return 0;
    }
    for(unsigned int i=0;i<size;i++){
            if(str[i]==ch){
                    count++;
            }
    }
    return count;
}

int main (int argc,char* array[]){
    string s="1 1 k";

    cout<<delimiter(s,' ') << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2020-07-30
    • 2020-04-11
    相关资源
    最近更新 更多