Dividir una cadena per algun delimitador és una tasca molt habitual. Per exemple, tenim una llista d'elements separats per comes d'un fitxer i volem elements individuals en una matriu.
Gairebé tots els llenguatges de programació proporcionen una funció que divideix una cadena per algun delimitador.
En 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;> }> |
>
llegir el fitxer excel en java
>
Output: Geeks for Geeks>
Complexitat temporal: O(n)
Espai auxiliar: O(n)
En 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.>
Mètode 1: Utilitzant l'API stringstream de C++
Requisit previ : corrent de corda API
L'objecte Stringstream es pot inicialitzar mitjançant un objecte de cadena, automàticament tokenitza cadenes a l'espai char. De la mateixa manera que cin stream stringstream us permet llegir una cadena com un flux de paraules. Alternativament, també podem utilitzar la funció getline per tokenitzar la cadena qualsevol delimitador de caràcters .
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>> — extreu una paraula del corrent.>
El codi següent ho demostra.
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>> paraula) {> > 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!>
Complexitat temporal: O(n)
Espai auxiliar: O(n)
On n és la longitud de la cadena d'entrada.
Mètode 2: utilitzant les API find() i substr() de C++.
Requisit previ: funció trobar i substr() .
Aquest mètode és més robust i pot analitzar una cadena amb qualsevol delimitador , no només espais (tot i que el comportament predeterminat és separar els espais). La lògica és bastant senzilla d'entendre a partir del codi següent.
java localdatetime
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 !>
Complexitat temporal: O(n)
Espai auxiliar: O (1)
On n és la longitud de la cadena d'entrada.
Mètode 3: utilitzant una cadena temporal
Si se us dóna que la longitud del delimitador és 1, només podeu utilitzar una cadena temporal per dividir la cadena. Això estalviarà el temps de sobrecàrrega de la funció en el cas del mètode 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;> }> |
>
>Sortida
geeks for geeks>
Complexitat temporal: O(n)
Espai auxiliar: O(n)
En Java:
A Java, split() és un mètode de la 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)>
Java
// 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);> > }> }> |
>
>
cadena separada en java
Sortida:
Geeks for-Geeks Geeks for Geeks>
Complexitat temporal: O(n)
Espai auxiliar: O(1)
En Python:
El mètode split() de Python retorna una llista de cadenes després de trencar la cadena donada pel separador especificat.
// regexp is the delimiting regular expression; // limit is limit the number of splits to be made str. split (regexp = '', limit = string.count(str))>
Python 3
line> => 'Geek1
Geek2
Geek3'> print> (line.split())> print> (line.split(> ' '> ,> 1> ))> |
>
>
Sortida:
['Geek1', 'Geek2', 'Geek3'] ['Geek1', ' Geek2 Geek3']>
Complexitat temporal: O(N) , ja que només travessa la cadena trobant tots els espais en blanc.
Espai auxiliar: O(1) , ja que no s'ha utilitzat espai addicional.