gpt4 book ai didi

c++ - 在空格上有选择地拆分字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:17 25 4
gpt4 key购买 nike

我的命令是:

move 1 "South Africa" "Europe"

代码:

do 
{
cut = text.find(' ');
if (cut == string::npos)
{
params.push_back(text);
}
else
{
params.push_back(text.substr(0, cut));
text = text.substr(cut + 1);
}
}
while (cut != string::npos);

问题是 South Africa 正在 split 成 SouthAfrica,我需要它保留 South Africa.

切割后的参数:

1, South, Africa, Europe

我需要它是:

1, South Africa, Europe

我该怎么做?用正则表达式?

命令的另一个例子:

move 3 "New Island" "South Afrika"

我的代码在 ' ' 之后被截断,我需要在我推回的参数中

3, New Island, South Africa

我的代码使得:

3,"New,Island","South,Africa"

最佳答案

您可以使用 std::stringstreamstd::getline 解析您的字符串

#include <iostream>
#include <sstream>
#include <string>

int main() {
std::string text("move 3 \"New Island\" \"South Afrika\"");
std::string command, count, country1, country2, temp;
std::stringstream ss(text);

ss >> command >> count;
ss.str("");
ss << text;
std::getline(ss, temp, '\"');
std::getline(ss, country1, '\"');
std::getline(ss, temp, '\"');
std::getline(ss, country2, '\"');

std::cout << command << ", " << count << ", " <<
country1 << ", " << country2 << std::endl;
return 0;
}

关于c++ - 在空格上有选择地拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17177361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com