LoginSignup
17
16

More than 5 years have passed since last update.

文字列を指定した区切り文字列で分割する関数

Posted at

C++ の標準ライブラリには文字列を分割する関数がないので作ってみました。
boost のアルゴリズムライブラリには split 関数が入っていますがこれだけのためにインクルードするのも面倒だなと。

コード

#include <string>

template <typename List>
void split(const std::string& s, const std::string& delim, List& result)
{
    result.clear();

    using string = std::string;
    string::size_type pos = 0;

    while(pos != string::npos )
    {
        string::size_type p = s.find(delim, pos);

        if(p == string::npos)
        {
            result.push_back(s.substr(pos));
            break;
        }
        else {
            result.push_back(s.substr(pos, p - pos));
        }

        pos = p + delim.size();
    }
}

// ====== SAMPLE ======
#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    std::vector<string> result;
    split("私の@@名前は@@太郎@@です@@", "@@", result);

    for(auto s : result) {
        cout << s << " / ";
    }
}
出力
私の / 名前は / 太郎 / です /  /

解説

split 関数の第一引数には分割対象文字列、第二引数には区切り文字列、分割結果を格納する第三引数 result には std::vector, std::list, std::deque など push_back が実装されているコンテナを入れます。

文字列分割関数というとカンマや空白など1文字を区切りにして分割するものが多いですが、この関数は "aaa", "XYZ", "$$" などの任意文字列を区切りに指定できるところが特徴(?)です。

17
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
16