From cb55987746c7461e3dc4ffe734c39ddefde5802a Mon Sep 17 00:00:00 2001 From: chatlanin Date: Mon, 15 Aug 2022 21:02:19 +0300 Subject: [PATCH] add split string to vector int --- bin/main.cpp | 3 +++ src/string/string.hpp | 21 +++++++++++++++++++++ tests/string.cpp | 6 ++++++ 3 files changed, 30 insertions(+) diff --git a/bin/main.cpp b/bin/main.cpp index c30048f..f93fe2e 100644 --- a/bin/main.cpp +++ b/bin/main.cpp @@ -45,9 +45,12 @@ int main(int argc, char *argv[]) { {// ex: string::split_str std::string str { "asdf,qwer,zxcv" }; + std::string str_int { "1 2 3" }; hack::string::v_str v = hack::string::split_str(str, ','); + auto v_int = hack::string::split_stoi(str_int, ' '); hack::log log; for (const auto& c : v) log(c); + for (const auto& c : v_int) log(c); std::string str_2 { "qqq,aaa:eee,ggg" }; hack::string::v_str v_2 = hack::string::split_str(str_2, ",:"); diff --git a/src/string/string.hpp b/src/string/string.hpp index 6a2b921..eb5d93d 100644 --- a/src/string/string.hpp +++ b/src/string/string.hpp @@ -9,6 +9,7 @@ namespace hack::string { using v_str = std::vector; + using v_int_str = std::vector; template v_str split_str(const std::string& str, T t) @@ -25,6 +26,26 @@ namespace hack::string end = str.find_first_of(t, begin); } v.emplace_back(str.substr(begin)); + + return v; + } + + template + 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; } } diff --git a/tests/string.cpp b/tests/string.cpp index 0d7d2d5..5896538 100644 --- a/tests/string.cpp +++ b/tests/string.cpp @@ -14,3 +14,9 @@ TEST(split_str, check) ASSERT_EQ(hack::string::split_str("qqq,aaa:eee,sss", ":,"), v1); } + +TEST(split_stoi, check) +{ + std::vector v { 1, 2, 3 }; + ASSERT_EQ(hack::string::split_stoi("1 2 3", ' '), v); +}