C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中

C++ Split a string by blank spaces unless it is enclosed in quotes and store in a vector

本文关键字:字符串 向量 存储 空间 空白 拆分      更新时间:2023-10-16

我有一个提示,可以获取用户输入。我想将此用户输入并将每个单词存储在向量中,通过空白空间分开,除非引号之间包含一组单词,在这种情况下,我希望各节中的所有术语都计算为1。p>例如,如果用户输入以下内容:

12345 Hello World "This is a group"

然后我希望向量存储以下内容:

vector[0] = 12345
vector[1] = Hello
vector[3] = World
vector[4] = "This is a group"

我有以下代码,该代码将用户输入按空白空间分配并将其存储在向量中,但是我很难弄清楚如何在引号中将所有文本计算为一个。

 string userInput
 cout << "Enter a string: ";
 getline(cin, userInput);
string buf; 
stringstream ss(userInput); 
vector<string> input;
while (ss >> buf){
    input.push_back(buf);

我想保留用户输入段落的单词的引号。我还想将结果保存到向量而不是将字符输出到屏幕上。

c 14已内置:http://en.cppreference.com/w/cpp/io/manip/quoted

活在coliru

#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
int main(void) {
    std::istringstream iss("12345 Hello World "This is a group"");
    std::vector<std::string> v;
    std::string s;
    while (iss >> std::quoted(s)) {
        v.push_back(s);
    }
    for(auto& str: v)
        std::cout << str << std::endl;
}

打印

12345
Hello
World
This is a group

这是一个工作示例:

#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main(void) {
    string str = "12345 Hello World "This is a group"";
    vector<string> v;
    size_t i = 0, j = 0, begin = 0;
    while(i < str.size()) {
        if(str[i] == ' ' || i == 0) {
            if(i + 1 < str.size() && str[i + 1] == '"') {
                j = begin + 1;
                while(j < str.size() && str[j++] != '"');
                v.push_back(std::string(str, begin, j - 1 - i));
                begin = j - 1;
                i = j - 1;
                continue;
            }
            j = begin + 1;
            while(j < str.size() && str[j++] != ' ');
            v.push_back(std::string(str, begin, j - 1 - i - (i ? 1 : 0) ));
            begin = j;
        }
        ++i;
    }
    for(auto& str: v)
        cout << str << endl;
    return 0;
}

输出:

12345
Hello
World
"This is a group"

但是,请注意此代码用于演示,因为它没有处理所有情况。例如,如果您输入中有双引号,则此while(j < str.size() && str[j++] != '"');将使整个字符串从该点拆分。