add split string to vector int

This commit is contained in:
chatlanin 2022-08-15 21:02:19 +03:00
parent aa468cc3d2
commit cb55987746
3 changed files with 30 additions and 0 deletions

View File

@ -45,9 +45,12 @@ int main(int argc, char *argv[])
{ {
{// ex: string::split_str {// ex: string::split_str
std::string str { "asdf,qwer,zxcv" }; std::string str { "asdf,qwer,zxcv" };
std::string str_int { "1 2 3" };
hack::string::v_str v = hack::string::split_str(str, ','); hack::string::v_str v = hack::string::split_str(str, ',');
auto v_int = hack::string::split_stoi(str_int, ' ');
hack::log log; hack::log log;
for (const auto& c : v) log(c); for (const auto& c : v) log(c);
for (const auto& c : v_int) log(c);
std::string str_2 { "qqq,aaa:eee,ggg" }; std::string str_2 { "qqq,aaa:eee,ggg" };
hack::string::v_str v_2 = hack::string::split_str(str_2, ",:"); hack::string::v_str v_2 = hack::string::split_str(str_2, ",:");

View File

@ -9,6 +9,7 @@
namespace hack::string namespace hack::string
{ {
using v_str = std::vector<std::string>; using v_str = std::vector<std::string>;
using v_int_str = std::vector<int>;
template<typename T> template<typename T>
v_str split_str(const std::string& str, T t) v_str split_str(const std::string& str, T t)
@ -25,6 +26,26 @@ namespace hack::string
end = str.find_first_of(t, begin); end = str.find_first_of(t, begin);
} }
v.emplace_back(str.substr(begin)); v.emplace_back(str.substr(begin));
return v;
}
template<typename T>
v_int_str split_stoi(const std::string& str, T t)
{
v_int_str v;
std::string::size_type begin = 0;
std::string::size_type end = str.find_first_of(t);
while(end != std::string::npos)
{
v.emplace_back(std::stoi(str.substr(begin, end - begin)));
begin = ++end;
end = str.find_first_of(t, begin);
}
v.emplace_back(std::stoi(str.substr(begin)));
return v; return v;
} }
} }

View File

@ -14,3 +14,9 @@ TEST(split_str, check)
ASSERT_EQ(hack::string::split_str("qqq,aaa:eee,sss", ":,"), v1); ASSERT_EQ(hack::string::split_str("qqq,aaa:eee,sss", ":,"), v1);
} }
TEST(split_stoi, check)
{
std::vector<int> v { 1, 2, 3 };
ASSERT_EQ(hack::string::split_stoi("1 2 3", ' '), v);
}