Dzielenie ciągu znaków za pomocą ogranicznika jest bardzo częstym zadaniem. Na przykład mamy listę elementów oddzielonych przecinkami z pliku i chcemy, aby poszczególne elementy znajdowały się w tablicy.
Prawie wszystkie języki programowania udostępniają funkcję podziału ciągu znaków za pomocą ogranicznika.
w 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;> }> |
>
wizualizator Java
>
Output: Geeks for Geeks>
Złożoność czasowa: NA)
Przestrzeń pomocnicza: NA)
W 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.>
Metoda 1: Korzystanie z API stringstream w C++
Warunek wstępny : strumień ciągów API
Obiekt Stringstream można zainicjować za pomocą obiektu string, dzieje się to automatycznie tokenizuje ciągi znaków spacji. Podobnie jak strumień cin stringstream umożliwia odczytanie ciągu znaków jako strumienia słów. Alternatywnie możemy również użyć funkcji getline do tokenizacji ciągu dowolny ogranicznik pojedynczego znaku .
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>> — wyodrębnia słowo ze strumienia.>
Poniższy kod to demonstruje.
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>> słowo) {> >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!>
Złożoność czasowa: O(n)
Przestrzeń pomocnicza: O(n)
Gdzie n jest długością ciągu wejściowego.
Metoda 2: Używanie funkcji API find() i substr() w języku C++.
Warunek wstępny: znajdź funkcję I substr() .
Ta metoda jest bardziej niezawodny i może analizować ciąg znaków z dowolnym ogranicznikiem , a nie tylko spacje (chociaż domyślnym zachowaniem jest oddzielanie spacjami). Logikę można dość łatwo zrozumieć z poniższego kodu.
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 !>
Złożoność czasowa: O(n)
Przestrzeń pomocnicza:O(1)
Gdzie n jest długością ciągu wejściowego.
Metoda 3: Używanie ciągu tymczasowego
Jeśli długość ogranicznika wynosi 1, możesz po prostu użyć łańcucha tymczasowego, aby podzielić ciąg. Pozwoli to zaoszczędzić czas funkcji w przypadku metody 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;> }> |
>
>Wyjście
harmonogram okrężny
geeks for geeks>
Złożoność czasowa: NA)
Przestrzeń pomocnicza: NA)
W Javie:
W Javie split() jest metodą w klasie 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)>
Jawa
uruchamianie skryptów w systemie Linux
// 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);> >}> }> |
>
>
Wyjście:
Geeks for-Geeks Geeks for Geeks>
Złożoność czasowa: NA)
Przestrzeń pomocnicza: O(1)
W Pythonie:
Metoda split() w Pythonie zwraca listę ciągów znaków po podzieleniu danego ciągu określonym separatorem.
// 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>))> |
>
>
Wyjście:
['Geek1', 'Geek2', 'Geek3'] ['Geek1', ' Geek2 Geek3']>
Złożoność czasowa: O(N) , ponieważ po prostu przechodzi przez ciąg znaków, znajdując wszystkie białe znaki.
Przestrzeń pomocnicza: O(1) , ponieważ nie wykorzystano dodatkowej przestrzeni.