일부 구분 기호로 문자열을 분할하는 것은 매우 일반적인 작업입니다. 예를 들어, 파일에서 쉼표로 구분된 항목 목록이 있고 배열에 개별 항목이 필요하다고 가정합니다.
거의 모든 프로그래밍 언어는 문자열을 구분 기호로 분할하는 기능을 제공합니다.
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);>
씨
// 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;> }> |
>
트리 순회
>
Output: Geeks for Geeks>
시간 복잡도 : 에)
보조 공간: 에)
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.>
방법 1: C++의 스트링스트림 API 사용
전제 조건 : 문자열 스트림 API
Stringstream 객체는 문자열 객체를 사용하여 초기화될 수 있으며 자동으로 공간 char에서 문자열을 토큰화합니다. cin 스트림과 마찬가지로 stringstream을 사용하면 문자열을 단어 스트림으로 읽을 수 있습니다. 또는 getline 함수를 활용하여 문자열을 토큰화할 수도 있습니다. 단일 문자 구분 기호 .
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>> — 스트림에서 단어를 추출합니다.>
아래 코드는 이를 보여줍니다.
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>> 단어) {> > 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!>
시간 복잡도: O(n)
보조 공간:O(n)
여기서 n은 입력 문자열의 길이입니다.
방법 2: C++ find() 및 substr() API 사용.
이 방법은 더욱 강력해지고 어떤 구분 기호로도 문자열을 구문 분석할 수 있습니다. , 공백뿐만 아니라(기본 동작은 공백으로 구분하는 것이지만) 아래 코드에서 논리를 이해하는 것은 매우 간단합니다.
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 !>
시간 복잡도: O(n)
보조공간:O(1)
여기서 n은 입력 문자열의 길이입니다.
방법 3: 임시 문자열 사용
구분 기호의 길이가 1인 경우 임시 문자열을 사용하여 문자열을 분할할 수 있습니다. 이렇게 하면 방법 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;> }> |
>
>산출
geeks for geeks>
시간 복잡도 : 에)
보조 공간: 에)
자바에서는:
Java에서 Split()은 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)>
자바
// 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);> > }> }> |
>
>
산출:
Geeks for-Geeks Geeks for Geeks>
시간 복잡도 : 에)
보조 공간: 오(1)
파이썬에서는:
Python의 Split() 메서드는 지정된 구분 기호로 주어진 문자열을 나눈 후 문자열 목록을 반환합니다.
// regexp is the delimiting regular expression; // limit is limit the number of splits to be made str. split (regexp = '', limit = string.count(str))>
파이썬3
C의 문자열
line> => 'Geek1
Geek2
Geek3'> print> (line.split())> print> (line.split(> ' '> ,> 1> ))> |
>
>
산출:
['Geek1', 'Geek2', 'Geek3'] ['Geek1', ' Geek2 Geek3']>
시간복잡도 : O(N) , 모든 공백을 찾기 위해 문자열을 순회하기 때문입니다.
보조공간 : O(1) , 추가 공간이 사용되지 않았기 때문입니다.