0
0

More than 5 years have passed since last update.

[C++] 文字列(String)を文字列delimiter(String)で分割

Last updated at Posted at 2019-08-11

動機

競技プログラミングに使えそうだったので

仕様

sprit_string(元の文字列, 区切り文字列)で、vector<string>を返します。
なお、区切り文字列が二つ続いた場合、空白文字を返します。

計算量

O(NM)
※元の文字列長: N 区切り文字列長: M

コード

テスト用のmain関数も合わせて置いておきます。

#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for (int i = 0; i < n; i++)
int i, j, k;

vector<string> sprit_string(string srcstr, string delim) {
  vector<string> result;

  string fragment = "";
  for (int i = 0; i < srcstr.length(); i++) {
    bool delimMatch = true;
    for (int j = 0; j < delim.length(); j++) {
      if (srcstr[i + j] != delim[j]) {
        delimMatch = false;
        break;
      }
    }

    if (delimMatch) {
      result.push_back(fragment);
      fragment = "";
      i += delim.length() - 1;
    } else {
      fragment.push_back(srcstr[i]);
    }
  }
  result.push_back(fragment);

  return result;
}

int main() {
  string S, delim;
  cin >> S >> delim;

  vector<string> splited_string = sprit_string(S, delim);

  REP(i, splited_string.size()) {
    cout << splited_string[i] << endl;
  }
}

実行例

input
delimtodaydelimisdelimadelimdelimbeautifuldelimday
delim
output
$ ./a.out < input

today
is
a

beautiful
day
0
0
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
0
0