C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中
C++ Split a string by blank spaces unless it is enclosed in quotes and store in a vector
我有一个提示,可以获取用户输入。我想将此用户输入并将每个单词存储在向量中,通过空白空间分开,除非引号之间包含一组单词,在这种情况下,我希望各节中的所有术语都计算为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++] != '"');
将使整个字符串从该点拆分。
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值