logo

Kuinka jakaa merkkijono C/C++:ssa, Pythonissa ja Javassa?

Merkkijonon jakaminen jollakin erottimella on hyvin yleinen tehtävä. Meillä on esimerkiksi pilkuilla eroteltu luettelo kohteista tiedostosta ja haluamme yksittäisiä kohteita taulukkoon.
Lähes kaikki ohjelmointikielet tarjoavat funktion, joka jakaa merkkijonon jollain erottimella.

C:ssa:

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



>

sql ddl -komennot

>

Output: Geeks for Geeks>

Aika monimutkaisuus: Päällä)

Aputila: Päällä)

C++:ssa

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

Tapa 1: C++:n stringstream API:n käyttäminen

Edellytys : stringstream API

Stringstream-objekti voidaan alustaa käyttämällä merkkijono-objektia, se automaattisesti tokenisoi merkkijonot välilyönnissä. Aivan kuten cin stream stringstream sallii sinun lukea merkkijonon sanavirtana. Vaihtoehtoisesti voimme myös käyttää getline-toimintoa merkkijonon tokenointiin mikä tahansa yksittäinen merkin erotin .

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>> — poimii sanan virrasta.>

Alla oleva koodi osoittaa sen.

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

Aika monimutkaisuus: O(n)

Aputila: O(n)

Missä n on syötetyn merkkijonon pituus.

Tapa 2: C++ find()- ja substr()-sovellusliittymien käyttäminen.

Edellytys: etsi toiminto ja substr() .

Tämä menetelmä on kestävämpi ja voi jäsentää merkkijonon millä tahansa erottimella , ei vain välilyöntejä (vaikka oletuskäyttäytyminen on erotella välilyönnillä.) Logiikka on melko helppo ymmärtää alla olevasta koodista.

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

Aika monimutkaisuus: O(n)

Aputila: O(1)

Missä n on syötetyn merkkijonon pituus.

Tapa 3: Väliaikaisen merkkijonon käyttö

Jos sinulle annetaan, että erottimen pituus on 1, voit yksinkertaisesti jakaa merkkijonon väliaikaisella merkkijonolla. Tämä säästää funktion ylimääräistä aikaa menetelmän 2 tapauksessa.

C++

osavaltiot Yhdysvalloissa




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

>

>

Lähtö

geeks for geeks>

Aika monimutkaisuus: Päällä)

Aputila: Päällä)

Javassa:
Javassa split() on String-luokan menetelmä.

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


kaksoislinkitetty lista



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

>

>

Lähtö:

Geeks for-Geeks Geeks for Geeks>

Aika monimutkaisuus: Päällä)
Aputila: O(1)

Pythonissa:
Pythonin split()-menetelmä palauttaa merkkijonoluettelon, kun annettu merkkijono on katkaistu määritetyllä erottimella.

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

>

>

Lähtö:

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

Aika monimutkaisuus: O(N) , koska se vain kulkee merkkijonon läpi löytääkseen kaikki välilyönnit.

Aputila: O(1) , koska ylimääräistä tilaa ei ole käytetty.