C++ 拆分字符串 [英] C++ split string

查看:36
本文介绍了C++ 拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用空格作为分隔符来分割字符串.我想将每个标记存储在一个数组或向量中.

I am trying to split a string using spaces as a delimiter. I would like to store each token in an array or vector.

我试过了.

    string tempInput;
    cin >> tempInput;
    string input[5];

    stringstream ss(tempInput); // Insert the string into a stream
    int i=0;
    while (ss >> tempInput){
        input[i] = tempInput;
        i++;
    }

问题是,如果我输入这是一个测试",数组似乎只存储输入[0] =这个".它不包含 input[2] 到 input[4] 的值.

The problem is that if i input "this is a test", the array only seems to store input[0] = "this". It does not contain values for input[2] through input[4].

我也尝试过使用向量,但结果相同.

I have also tried using a vector but with the same result.

推荐答案

转到重复题学习如何将字符串拆分为单词,但您的方法实际上是正确的.实际问题在于您如何在尝试拆分输入之前 读取它:

Go to the duplicate questions to learn how to split a string into words, but your method is actually correct. The actual problem lies in how you are reading the input before trying to split it:

string tempInput;
cin >> tempInput; // !!!

当您使用 cin >>tempInput,您只能从输入中获取第一个单词,而不是整个文本.有两种可能的方法来解决这个问题,其中最简单的方法是忘记 stringstream 并直接迭代输入:

When you use the cin >> tempInput, you are only getting the first word from the input, not the whole text. There are two possible ways of working your way out of that, the simplest of which is forgetting about the stringstream and directly iterating on input:

std::string tempInput;
std::vector< std::string > tokens;
while ( std::cin >> tempInput ) {
   tokens.push_back( tempInput );
}
// alternatively, including algorithm and iterator headers:
std::vector< std::string > tokens;
std::copy( std::istream_iterator<std::string>( std::cin ),
           std::istream_iterator<std::string>(),
           std::back_inserter(tokens) );

这种方法将在单个向量中为您提供输入中的所有标记.如果您需要单独处理每一行,那么您应该使用 <string> 标头中的 getline 而不是 cin >>临时输入:

This approach will give you all the tokens in the input in a single vector. If you need to work with each line separatedly then you should use getline from the <string> header instead of the cin >> tempInput:

std::string tempInput;
while ( getline( std::cin, tempInput ) ) { // read line
   // tokenize the line, possibly with your own code or 
   // any answer in the 'duplicate' question
}

这篇关于C++ 拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆