C/C++、Python、Java で文字列を分割するにはどうすればよいですか?

文字列を区切り文字で分割するのは非常に一般的なタスクです。たとえば、ファイルからの項目のカンマ区切りリストがあり、配列内の個々の項目が必要だとします。
ほとんどすべてのプログラミング言語には、文字列を区切り文字で分割する関数が用意されています。

C の場合:

// Splits str[] according to given delimiters. // and returns next token. It needs to be called // in a loop to get all tokens. It returns NULL // when there are no more tokens. char * strtok(char str[], const char *delims); 

C




// A C/C++ program for splitting a string> // using strtok()> #include> #include> int> main()> {> > char> str[] => 'Geeks-for-Geeks'> ;> > // Returns first token> > char> *token => strtok> (str,> '-'> );> > > // Keep printing tokens while one of the> > // delimiters present in str[].> > while> (token != NULL)> > {> > printf> (> '%s '> , token);> > token => strtok> (NULL,> '-'> );> > }> > return> 0;> }>

Output: Geeks for Geeks 

時間計算量 : の上)

補助スペース: の上)

C++の場合

Note: The main disadvantage of strtok() is that it only works for C style strings. Therefore we need to explicitly convert C++ string into a char array. Many programmers are unaware that C++ has two additional APIs which are more elegant and works with C++ string. 

方法 1: C++のstringstream APIを使用する

前提条件 : ストリングストリーム API

Stringstream オブジェクトは文字列オブジェクトを使用して初期化でき、自動的に初期化されます。 スペース文字で文字列をトークン化します。 cin stream と同様に、stringstream を使用すると、文字列を単語のストリームとして読み取ることができます。あるいは、getline 関数を利用して文字列をトークン化することもできます。 任意の 1 文字の区切り文字

Some of the Most Common used functions of StringStream. clear() — flushes the stream str() — converts a stream of words into a C++ string object. operator  < <— pushes a string object into the stream. operator>> — ストリームから単語を抽出します。> 

以下のコードはそれを示しています。

C++




#include> using> namespace> std;> // A quick way to split strings separated via spaces.> void> simple_tokenizer(string s)> {> > stringstream ss(s);> > string word;> > while> (ss>> 単語) {>> > cout < < word < < endl;> > }> }> // A quick way to split strings separated via any character> // delimiter.> void> adv_tokenizer(string s,> char> del)> {> > stringstream ss(s);> > string word;> > while> (!ss.eof()) {> > getline(ss, word, del);> > cout < < word < < endl;> > }> }> int> main(> int> argc,> char> const> * argv[])> {> > string a => 'How do you do!'> ;> > string b => 'How$do$you$do!'> ;> > // Takes only space separated C++ strings.> > simple_tokenizer(a);> > cout < < endl;> > adv_tokenizer(b,> '$'> );> > cout < < endl;> > return> 0;> }>

Output : How do you do! 

時間計算量: O(n)

補助スペース:O(n)

ここで、n は入力文字列の長さです。

方法 2: C++ find() および substr() API を使用する。

前提条件: 検索関数 そして 部分文字列()

この方法は より堅牢で、任意の区切り文字を含む文字列を解析できます 、スペースだけではありません (ただし、デフォルトの動作はスペースで区切られます)。ロジックは、以下のコードから理解するのが非常に簡単です。

C++




#include> using> namespace> std;> void> tokenize(string s, string del => ' '> )> {> > int> start, end = -1*del.size();> > do> {> > start = end + del.size();> > end = s.find(del, start);> > cout < < s.substr(start, end - start) < < endl;> > }> while> (end != -1);> }> int> main(> int> argc,> char> const> * argv[])> {> > // Takes C++ string with any separator> > string a => 'How$%do$%you$%do$%!'> ;> > tokenize(a,> '$%'> );> > cout < < endl;> > return> 0;> }>

Output: How do you do ! 

時間計算量: O(n)

補助スペース:O(1)

ここで、n は入力文字列の長さです。

方法 3: 一時文字列を使用する

区切り文字の長さが 1 である場合は、一時文字列を使用して文字列を分割するだけで済みます。これにより、方法 2 の場合、関数のオーバーヘッド時間が節約されます。

C++




#include> using> namespace> std;> void> split(string str,> char> del){> > // declaring temp string to store the curr 'word' upto del> > string temp => ''> ;> > > for> (> int> i=0; i <(> int> )str.size(); i++){> > // If cur char is not del, then append it to the cur 'word', otherwise> > // you have completed the word, print it, and start a new word.> > if> (str[i] != del){> > temp += str[i];> > }> > else> {> > cout < < temp < <> ' '> ;> > temp => ''> ;> > }> > }> > > cout < < temp;> }> int> main() {> > string str => 'geeks_for_geeks'> ;> // string to be split> > char> del => '_'> ;> // delimiter around which string is to be split> > > split(str, del);> > > return> 0;> }>

出力

geeks for geeks 

時間計算量 : の上)

補助スペース: の上)

Java の場合:
Java では、split() は String クラスのメソッドです。

// expregexp is the delimiting regular expression; // limit is the number of returned strings public String[] split (String regexp, int limit); // We can call split() without limit also public String[] split (String regexp) 

ジャワ




// A Java program for splitting a string> // using split()> import> java.io.*;> public> class> Test> {> > public> static> void> main(String args[])> > {> > String Str => new> String(> 'Geeks-for-Geeks'> );> > // Split above string in at-most two strings> > for> (String val: Str.split(> '-'> ,> 2> ))> > System.out.println(val);> > System.out.println(> ''> );> > > // Splits Str into all possible tokens> > for> (String val: Str.split(> '-'> ))> > System.out.println(val);> > }> }>

出力:

Geeks for-Geeks Geeks for Geeks 

時間計算量 : の上)
補助スペース: ○(1)

Python の場合:
Python の Split() メソッドは、指定された文字列を指定された区切り文字で分割した後の文字列のリストを返します。

 // regexp is the delimiting regular expression; // limit is limit the number of splits to be made str. split (regexp = '', limit = string.count(str)) 

Python3




line> => 'Geek1 Geek2 Geek3'> print> (line.split())> print> (line.split(> ' '> ,> 1> ))>

出力:

['Geek1', 'Geek2', 'Geek3'] ['Geek1', '
Geek2 
Geek3'] 

時間計算量 : O(N) 文字列を走査してすべての空白を見つけるだけであるためです。

補助スペース : O(1) 余分なスペースが使用されていないためです。