Het splitsen van een tekenreeks door een scheidingsteken is een veel voorkomende taak. We hebben bijvoorbeeld een door komma's gescheiden lijst met items uit een bestand en we willen individuele items in een array.
Bijna alle programmeertalen bieden een functie die een tekenreeks door een scheidingsteken splitst.
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;> }> |
>
apurva padgaonkar
>
Output: Geeks for Geeks>
Tijdcomplexiteit: Op)
Hulpruimte: Op)
In 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.>
Methode 1: Met behulp van de stringstream-API van C++
Voorwaarde : stringstroom API
Het Stringstream-object kan automatisch worden geïnitialiseerd met behulp van een string-object tokeniseert tekenreeksen op spatietekens. Net zoals je met cin stream met stringstream een string kunt lezen als een stroom woorden. Als alternatief kunnen we ook de getline-functie gebruiken om de string te tokeniseren elk afzonderlijk tekenscheidingsteken .
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>> — haalt een woord uit de stream.>
De onderstaande code demonstreert het.
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>> woord) {> >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!>
Tijdcomplexiteit: O(n)
Hulpruimte:O(n)
Waarbij n de lengte van de invoerreeks is.
Methode 2: C++ find() en substr() API's gebruiken.
Voorwaarde: functie vinden En substr() .
Deze methode is robuuster en kan een tekenreeks met elk scheidingsteken ontleden , niet alleen spaties (hoewel het standaardgedrag is om op spaties te scheiden.) De logica is vrij eenvoudig te begrijpen uit de onderstaande code.
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 !>
Tijdcomplexiteit: O(n)
Hulpruimte:O(1)
Waarbij n de lengte van de invoerreeks is.
Methode 3: Tijdelijke tekenreeks gebruiken
Als u krijgt dat de lengte van het scheidingsteken 1 is, kunt u eenvoudigweg een tijdelijke tekenreeks gebruiken om de tekenreeks te splitsen. Dit bespaart de functie overheadtijd in het geval van methode 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;> }> |
>
>Uitvoer
ms word snelle toegang werkbalk
geeks for geeks>
Tijdcomplexiteit: Op)
Hulpruimte: Op)
Op Java:
In Java is split() een methode in de String-klasse.
// 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
mama kulkarni
// 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);> >}> }> |
>
>
Uitgang:
Geeks for-Geeks Geeks for Geeks>
Tijdcomplexiteit: Op)
Hulpruimte: O(1)
In Python:
De methode split() in Python retourneert een lijst met tekenreeksen nadat de gegeven tekenreeks is verbroken met het opgegeven scheidingsteken.
// 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>))> |
>
>
Uitgang:
['Geek1', 'Geek2', 'Geek3'] ['Geek1', ' Geek2 Geek3']>
Tijdcomplexiteit: O(N) , omdat het gewoon door de string loopt en alle witruimte vindt.
Hulpruimte: O(1) , aangezien er geen extra ruimte is gebruikt.