【C++】カンマ区切りの文字列std::stringを分割する
std::string型の文字列に対して、指定した文字列を区切り目として分割する実装を公開します。
カンマ区切りされた文字列から、欲しい情報だけを抜き出す際などに便利だと思います。
概要
- std::string型の文字列を、指定の文字列を区切りとして分割
- 区切った文字列をstd::vector<std::string>型に格納
ソースコード
#include <iostream> #include <string> #include <vector> std::vector<std::string> SplitSentence(std::string sentence, std::string delimiter) { std::vector<std::string> words; size_t position = 0; while(sentence.find(delimiter.c_str(), position) != std::string::npos){ size_t next_position = sentence.find(delimiter.c_str(), position); std::string word = sentence.substr(position, next_position-position); position = next_position + delimiter.length(); words.push_back(word); // std::cout << "word.c_str() = " << word.c_str() << std::endl; } std::string last_word = sentence.substr(position, sentence.length()-position); words.push_back(last_word); // std::cout << "last_word.c_str() = " << last_word.c_str() << std::endl; std::cout << "input: " << sentence.c_str() << std::endl; for(size_t i=0;i<words.size();i++) std::cout << "words[" << i << "] = " << words[i].c_str() << std::endl; return words; } int main(int argc, char** argv) { std::string sentence = "3, 2, 1, hello world!"; std::vector<std::string> splitted_sentence = SplitSentence(sentence, std::string(", ")); }
解説
- 関数 std::vector<std::string> SplitSentence(std::string sentence, std::string delimiter)
- 引数1:分割したい元の文字列
- 引数2:区切り目にする文字列
- 返り値:分割された文字列のベクトル
- .find(引数1, 引数2)
- 指定の文字列の位置を調べられる
- 引数1:探したい文字列
- 引数2:その位置から探し始める
- 返り値:探したい文字列の位置
見つからなかった場合はstd::string::npos - .substr(引数1, 引数2)
- 引数1の位置から引数2の長さの文字列を抽出できる
- 引数1:抽出の開始位置
- 引数2:抽出する長さ
- 返り値:抽出した文字列
さいごに
参考になれば幸いです。
以上です。
Ad.
コメント