C++の改行で文字列を分割する
この投稿では、C++で改行で文字列を分割する方法について説明します。
1.使用する std::getline
改行で文字列を分割する簡単な解決策は、 std::getline 関数。以下に示すように、改行で区切られた入力ストリームからトークンを抽出するために使用できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <string> #include <vector> #include <regex> std::vector<std::string> splitString(const std::string& str) { std::vector<std::string> tokens; std::stringstream ss(str); std::string token; while (std::getline(ss, token, '\n')) { tokens.push_back(token); } return tokens; } int main() { std::string str = "C\nC++\nJava"; std::vector<std::string> tokens = splitString(str); for (auto const &token: tokens) { std::cout << token << std::endl; } return 0; } |
出力:
C
C++
Java
2.使用する string::find
The std::string::find
メンバー関数は、指定された位置から開始して、指定された文字の文字列を検索します。指定された文字の最初の出現を返し、 string::npos
見つからない場合。改行で文字列を分割するには、次のように使用できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> #include <string> #include <vector> std::vector<std::string> splitString(const std::string& str) { std::vector<std::string> tokens; std::string::size_type pos = 0; std::string::size_type prev = 0; while ((pos = str.find('\n', prev)) != std::string::npos) { tokens.push_back(str.substr(prev, pos - prev)); prev = pos + 1; } tokens.push_back(str.substr(prev)); return tokens; } int main() { std::string str = "C\nC++\nJava"; std::vector<std::string> tokens = splitString(str); for (auto const &token: tokens) { std::cout << token << std::endl; } return 0; } |
出力:
C
C++
Java
3.Boostの使用
最後に、 boost::algorithm::split_regex
入力シーケンスを区切り文字で区切られたトークンに分割するためにブーストライブラリによって提供されるアルゴリズム。この関数はCstrtokと同等であり、ヘッダーで使用できます。 <boost/algorithm/string/regex.hpp>
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <string> #include <vector> #include <regex> #include <boost/regex.hpp> #include <boost/algorithm/string/regex.hpp> std::vector<std::string> splitString(const std::string& str) { std::vector<std::string> tokens; split_regex(tokens, str, boost::regex("(\r\n)+")); return tokens; } int main() { std::string str = "C\nC++\nJava"; std::vector<std::string> tokens = splitString(str); for (auto const &token: tokens) { std::cout << token << std::endl; } return 0; } |
出力:
C
C++
Java
これで、C++の改行で文字列を分割できます。