1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c++でsplit関数を秒で実装してみた

Last updated at Posted at 2019-02-22

c++にはsplit関数がない

 なんでかは分かりませんがc++を作ってる偉い人がsplit関数は静的言語のc++の理念には沿わないからだとかなんとか。
 stringのfind関数使えばsplitっぽいものが作れそうだったので自分の備忘録的な感じで置いときます。

split関数実装

例えばこんな例、「文章なる文字列sを一つ与えられた時にカンマ(,)をスペース(空白)で置き換えたい」としよう。これをstringのfind関数を使って書くとこうなる。

sample01.cpp
# include <iostream>
# include <string> // VC++ではこいつ入れないとコンパイル通らない
using namespace std;

int main() {
    string s;
    cin >> s; // 標準入力例 "hoge,hoge,hoge"
    
    size_t i = s.find(","); // 文章の先頭からカンマの位置を探す(最初に見つかるカンマ1つだけ)
    s[i] = *" "; // 空白で埋める。*忘れないように注意
    
    cout << s << endl; // 標準出力例 "hoge hoge,hoge"
    
    return 0;
}

 先頭のカンマだけとは言わず、文章sからすべてのカンマをスペースに置き換えたいならwhile文を使えばよい。find関数は文字列s内に探したい文字列がない場合は-1を返してくるので、これをwhileの継続条件にしてやる。
※追記:-1はstring::nposとして実装されているそうなので、どっちを使ってもよい

sample02.cpp
# include <iostream>
# include <string> // VC++ではこいつ入れないとコンパイル通らない
using namespace std;

int main() {
    string s;
    cin >> s; // 入力 "hoge,hoge,hoge"

    // カンマ駆逐
    while (s.find(",") != -1) { // カンマが見つからなくなるまで
        s[s.find(",")] = *" "; // find関数をそのままsの添え字にして行間短縮
    }

    cout << s << endl; // 出力 "hoge hoge hoge" カンマが全て空白に置き換わった
	
    return 0;
}

 以上クソ丁寧に解説してみました。質問や改良案などあればコメントください。

1
0
3

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?