logo

Come dividere una stringa in C/C++, Python e Java?

Dividere una stringa in base a un delimitatore è un compito molto comune. Ad esempio, abbiamo un elenco di elementi separati da virgole da un file e vogliamo singoli elementi in un array.
Quasi tutti i linguaggi di programmazione forniscono una funzione che divide una stringa con un delimitatore.

In 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;> }>



>

pseudocodice Java

>

Output: Geeks for Geeks>

Complessità temporale: SU)

Spazio ausiliario: SU)

Nel 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.>

Metodo 1: Utilizzando l'API stringstream di C++

Prerequisito : stringstream API

L'oggetto Stringstream può essere inizializzato automaticamente utilizzando un oggetto stringa tokenizza le stringhe sul carattere spazio. Proprio come cin stream, stringstream ti consente di leggere una stringa come un flusso di parole. In alternativa, possiamo anche utilizzare la funzione getline per tokenizzare la stringa qualsiasi delimitatore di carattere singolo .

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>> — estrae una parola dallo stream.>

Il codice seguente lo dimostra.

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>> parola) {> >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!>

Complessità temporale: O(n)

Spazio ausiliario:O(n)

Dove n è la lunghezza della stringa di input.

Metodo 2: utilizzo delle API C++ find() e substr().

Prerequisito: trova la funzione E sottostr() .

Questo metodo è più robusto e può analizzare una stringa con qualsiasi delimitatore , non solo spazi (sebbene il comportamento predefinito sia separare gli spazi). La logica è piuttosto semplice da comprendere dal codice seguente.

amisha patel

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 !>

Complessità temporale: O(n)

Spazio ausiliario:O(1)

Dove n è la lunghezza della stringa di input.

Metodo 3: utilizzo di una stringa temporanea

Se ti viene dato che la lunghezza del delimitatore è 1, puoi semplicemente utilizzare una stringa temporanea per dividere la stringa. Ciò farà risparmiare tempo alla funzione nel caso del metodo 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;> }>

>

>

Produzione

geeks for geeks>

Complessità temporale: SU)

Spazio ausiliario: SU)

In Giava:
In Java, split() è un metodo nella classe 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)>

Giava




// 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);> >}> }>

>

>

errore semantico

Produzione:

Geeks for-Geeks Geeks for Geeks>

Complessità temporale: SU)
Spazio ausiliario: O(1)

In Python:
Il metodo split() in Python restituisce un elenco di stringhe dopo aver spezzato la stringa data con il separatore specificato.

 // 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>))>

>

>

Produzione:

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

Complessità temporale: O(N) , poiché attraversa semplicemente la stringa trovando tutti gli spazi bianchi.

Spazio ausiliario: O(1) , poiché non è stato utilizzato spazio aggiuntivo.