我有一个字符串s
。我想从这个字符串中提取co-ordinates
例如
string s = "(94 * SCALE, 10 * SCALE, 62 * SCALE, 10 * SCALE);"
我想从这个字符串中提取94、10、62和10。
为此,我编写了Split()
,它非常有效
为此:
我首先在,
的基础上拆分字符串。
然后,我再次在*
的基础上对字符串进行拆分。
这是我的代码:
std::vector<std::string> Split(std::string& s, char delim)
{
std::stringstream ss(s);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim))
elems.push_back(item);
return elems;
}
vector<int> GetTheCoordinates(std::vector<std::string>& splittedString)
{
vector<int> vec;
for (unsigned long j = 0; j < splittedString.size(); j++)
{
std::vector<std::string> finalString = Split(splittedString[j], '*');
int leftValue = stoi(finalString[0]);
vec.push_back(leftValue);
}
return vec;
}
int main()
{
string str = "(94 * SCALE, 10 * SCALE, 62 * SCALE, 10 * SCALE);"
std::string s = str.substr(1, str.size() - 3); // removing ( and ); from str
std::vector<std::string> splittedString = Split(s, ',');
std::vector<int> vec = GetTheCoordinates(splittedString);
}
上面的代码有效,我得到了坐标
这里的问题是:
当我尝试拆分时,我假设字符串将包含
,
,
的基础,并假设当我尝试拆分时它将具有*
在CCD_ 9的基础上。但如果这两次字符串都没有,
呢以及CCD_ 11,但是一些其它符号。然后如何使用try-catch
?我用过
stoi(finalString[0]);
,但如果字符串不能进行整数转换。然后如何使用try-catch
?
输入:字符串str="(94*比例尺和10*比例尺,62*比例尺,10*比例尺(">
输出:行应该有,
而不是&
。
输入字符串str=";(94&比例尺,10*比例尺,62*比例尺,10*比例尺(">
输出:线路应具有*
而非&
不确定这是否是您想要的答案。
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
int main()
{
std::string s = "(94 * SCALE, 10 * SCALE, 62 * SCALE, 10 * SCALE);";
s = s.substr(1);
std::vector<std::string> container;
boost::split(container, s, boost::is_any_of("*,"));
// want to extract
std::vector<int> vals;
for (auto item : container) {
try {
int val = std::stoi(item.c_str());
vals.push_back(val);
}
catch (std::invalid_argument const& ex) {
std::cout << "std::invalid_argument::what(): " << ex.what() << 'n';
}
catch (std::out_of_range const& ex) {
std::cout << "std::out_of_range::what(): " << ex.what() << 'n';
}
}
std::cout << "nwant to extract:n";
for (auto val : vals) {
std::cout << val << std::endl;
}
return 0;
}
输出:
std::invalid_argument::what(): invalid stoi argument
std::invalid_argument::what(): invalid stoi argument
std::invalid_argument::what(): invalid stoi argument
std::invalid_argument::what(): invalid stoi argument
want to extract:
94
10
62
10