logo

C++에서 문자열을 분할하는 방법은 무엇입니까?

이 항목에서는 주어진 문자열을 단일 단어로 분할하는 방법에 대해 설명합니다. C++ 프로그래밍 언어 . 단어 그룹이나 문자열 모음을 단일 단어로 나눌 때 이를 나뉘다 또는 문자열의 분할. 그러나 문자열 분리는 공백( ), 쉼표(,), 하이픈(-) 등과 같은 일부 구분 기호를 사용하여 단어를 개별적으로 만드는 경우에만 가능합니다. 게다가 문자열 모음을 개별 문자열로 나누는 미리 정의된 분할 함수도 없습니다. 따라서 여기서는 C++에서 문자열을 단일 문자열로 분할하는 다양한 방법을 알아봅니다.

C++에서 문자열을 분할하는 방법

C++에서 문자열을 분할하는 다른 방법

  1. strtok() 함수를 사용하여 문자열 분할
  2. 사용자 정의 Split() 함수를 사용하여 문자열 분할
  3. std::getline() 함수를 사용하여 문자열 분할
  4. find() 및 substr() 함수를 사용하여 문자열 분할

strtok() 함수를 사용하여 문자열 분할

strtok(): strtok() 함수는 전달된 구분 기호를 기반으로 원래 문자열을 조각이나 토큰으로 분할하는 데 사용됩니다.

통사론

 char *ptr = strtok( str, delim) 

위 구문에서 strtok()에는 두 개의 매개변수가 있습니다. str , 그리고 나는 공유한다 .

str : str은 strtok() 함수가 문자열을 분할하는 원본 문자열입니다.

java 문자열을 int로 캐스트

나는 공유한다 : 문자열을 분할하는 데 사용되는 문자입니다. 예를 들어 쉼표(,), 공백( ), 하이픈(-) 등이 있습니다.

반품 : 다음 문자 토큰을 참조하는 포인터를 반환합니다. 처음에는 문자열의 첫 번째 토큰을 가리킵니다.

참고: strtok() 함수는 원래 문자열을 수정하고 strtok() 함수를 호출할 때마다 구분 기호 위치에 NULL 문자('')를 넣습니다. 이런 방식으로 토큰의 상태를 쉽게 추적할 수 있습니다.

strtok() 함수를 사용하여 문자열을 분할하는 프로그램

strtok() 함수를 사용하여 C++에서 문자열을 분할하는 예를 고려해 보겠습니다.

소누 니감

프로그램.cpp

 #include #include using namespace std; int main() { char str[100]; // declare the size of string cout &lt;&lt; &apos; Enter a string: &apos; &lt;<endl; cin.getline(str, 100); use getline() function to read a string from input stream char *ptr; declare ptr pointer ' , '); strtok() separate using comma (,) delimiter. cout << 
 split function: endl; while loop check is not null (ptr !="NULL)" { print the token (null, } return 0; < pre> <p> <strong>Output</strong> </p> <pre> Enter a string: Learn how to split a string in C++ using the strtok() function. Split string using strtok() function: Learn how to split a string in C++ Using the strtok() function. </pre> <h3>Program to use custom split() function to split strings</h3> <p>Let&apos;s write a program to split sequences of strings in C++ using a custom split() function.</p> <p> <strong>Program2.cpp</strong> </p> <pre> #include #include #define max 8 // define the max string using namespace std; string strings[max]; // define max string // length of the string int len(string str) { int length = 0; for (int i = 0; str[i] != &apos;&apos;; i++) { length++; } return length; } // create custom split() function void split (string str, char seperator) { int currIndex = 0, i = 0; int startIndex = 0, endIndex = 0; while (i <= len(str)) { if (str[i]="=" seperator || i="=" endindex="i;" string substr ; substr.append(str, startindex, - startindex); strings[currindex]="subStr;" currindex +="1;" startindex="endIndex" 1; } i++; int main() str="Program to split strings using custom split function." char space split(str, seperator); cout <<' the split is: '; for (int < max; i++) << '
 : ' strings[i]; return 0; pre> <p> <strong>Output</strong> </p> <pre> The split string is: i : 0 Program i : 1 to i : 2 split i : 3 strings i : 4 using i : 5 custom i : 6 split i : 7 function. </pre> <h3>Use std::getline() function to split string</h3> <p>A getline() function is a standard library function of C++ used to read the string from an input stream and put them into the vector string until delimiter characters are found. We can use <strong>std::getline()</strong> function by importing the header file.</p> <p> <strong>Syntax</strong> </p> <pre> getline(str, token, delim); </pre> <p>It has three parameters:</p> <p> <strong>str:</strong> A str is a variable that stores original string.</p> <p> <strong>token:</strong> It stores the string tokens extracted from original string.</p> <p> <strong>delim:</strong> It is a character that are used to split the string. For example, comma (,), space ( ), hyphen (-), etc.</p> <h3>Program to use getline() function to split strings</h3> <p>Let&apos;s consider an example to split strings using the getline() function in C++.</p> <p> <strong>Program3.cpp</strong> </p> <pre> #include #include #include #include using namespace std; int main() { string S, T; // declare string variables getline(cin, S); // use getline() function to read a line of string and store into S variable. stringstream X(S); // X is an object of stringstream that references the S string // use while loop to check the getline() function condition while (getline(X, T, &apos; &apos;)) { /* X represents to read the string from stringstream, T use for store the token string and, &apos; &apos; whitespace represents to split the string where whitespace is found. */ cout &lt;&lt; T &lt;&lt; endl; // print split string } return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Welcome to the JavaTpoint and Learn C++ Programming Language. Welcome to the JavaTpoint and Learn C++ Programming Language. </pre> <h3>Program to split the given string using the getline() function</h3> <p>Let&apos;s consider an example to split a given string in C++ using the getline() function.</p> <p> <strong>Program4.cpp</strong> </p> <pre> #include #include #include #include void split_str( std::string const &amp;str, const char delim, std::vector &amp;out ) { // create a stream from the string std::stringstream s(str); std::string s2; while (std:: getline (s, s2, delim) ) { out.push_back(s2); // store the string in s2 } } int main() { std:: string s2 = &apos;Learn How to split a string in C++&apos;; const char delim = &apos; &apos;; /* define the delimiter like space (&apos; &apos;), comma (,), hyphen (-), etc. */ std::cout &lt;&lt; &apos;Your given string is: &apos; &lt;&lt; s2; std::vector out; // store the string in vector split_str (s2, delim, out); // call function to split the string // use range based for loop for (const auto &amp;s2: out) { std::cout &lt;&lt; &apos;
&apos; &lt;&lt; s2; } return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Your given string is: Learn How to split a string in C++ Learn How to split a string in C++ </pre> <h3>Use find() and substr() function to split strings</h3> <p>Let&apos;s write a program to use find() function and substr() function to split given strings in C++.</p> <p> <strong>Program4.cpp</strong> </p> <pre> #include #include using namespace std; int main() { // given string with delimiter string given_str = &apos;How_to_split_a_string_using_find()_and_substr()_function_in_C++&apos;; string delim = &apos;_&apos;; // delimiter cout &lt;&lt; &apos; Your string with delimiter is: &apos; &lt;&lt; given_str &lt;&lt; endl; size_t pos = 0; string token1; // define a string variable // use find() function to get the position of the delimiters while (( pos = given_str.find (delim)) != std::string::npos) { token1 = given_str.substr(0, pos); // store the substring cout &lt;&lt; token1 &lt;&lt; endl; given_str.erase(0, pos + delim.length()); /* erase() function store the current positon and move to next token. */ } cout &lt;&lt; given_str &lt;&lt; endl; // it print last token of the string. } </pre> <p> <strong>Output</strong> </p> <pre> Your string with delimiter is: How_to_split_a_string_using_find()_and_substr()_function_in_C++ How to split a string using find() and substr() function in C++ </pre> <p>In the above program, we use a <strong>find()</strong> function inside the loop to repeatedly find the occurrence of the delimiter in the given string and then split it into tokens when the delimiter occurs. And the <strong>substr()</strong> function stores the sub-string to be printed. On the other hand, an erase() function stores the current position of the string and moves to the next token, and this process continues until we have got all the split strings.</p> <hr></=></pre></endl;>

사용자 정의 Split() 함수를 사용하여 문자열을 분할하는 프로그램

사용자 정의 Split() 함수를 사용하여 C++에서 문자열 시퀀스를 분할하는 프로그램을 작성해 보겠습니다.

프로그램2.cpp

 #include #include #define max 8 // define the max string using namespace std; string strings[max]; // define max string // length of the string int len(string str) { int length = 0; for (int i = 0; str[i] != &apos;&apos;; i++) { length++; } return length; } // create custom split() function void split (string str, char seperator) { int currIndex = 0, i = 0; int startIndex = 0, endIndex = 0; while (i <= len(str)) { if (str[i]="=" seperator || i="=" endindex="i;" string substr ; substr.append(str, startindex, - startindex); strings[currindex]="subStr;" currindex +="1;" startindex="endIndex" 1; } i++; int main() str="Program to split strings using custom split function." char space split(str, seperator); cout <<\' the split is: \'; for (int < max; i++) << \'
 : \' strings[i]; return 0; pre> <p> <strong>Output</strong> </p> <pre> The split string is: i : 0 Program i : 1 to i : 2 split i : 3 strings i : 4 using i : 5 custom i : 6 split i : 7 function. </pre> <h3>Use std::getline() function to split string</h3> <p>A getline() function is a standard library function of C++ used to read the string from an input stream and put them into the vector string until delimiter characters are found. We can use <strong>std::getline()</strong> function by importing the header file.</p> <p> <strong>Syntax</strong> </p> <pre> getline(str, token, delim); </pre> <p>It has three parameters:</p> <p> <strong>str:</strong> A str is a variable that stores original string.</p> <p> <strong>token:</strong> It stores the string tokens extracted from original string.</p> <p> <strong>delim:</strong> It is a character that are used to split the string. For example, comma (,), space ( ), hyphen (-), etc.</p> <h3>Program to use getline() function to split strings</h3> <p>Let&apos;s consider an example to split strings using the getline() function in C++.</p> <p> <strong>Program3.cpp</strong> </p> <pre> #include #include #include #include using namespace std; int main() { string S, T; // declare string variables getline(cin, S); // use getline() function to read a line of string and store into S variable. stringstream X(S); // X is an object of stringstream that references the S string // use while loop to check the getline() function condition while (getline(X, T, &apos; &apos;)) { /* X represents to read the string from stringstream, T use for store the token string and, &apos; &apos; whitespace represents to split the string where whitespace is found. */ cout &lt;&lt; T &lt;&lt; endl; // print split string } return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Welcome to the JavaTpoint and Learn C++ Programming Language. Welcome to the JavaTpoint and Learn C++ Programming Language. </pre> <h3>Program to split the given string using the getline() function</h3> <p>Let&apos;s consider an example to split a given string in C++ using the getline() function.</p> <p> <strong>Program4.cpp</strong> </p> <pre> #include #include #include #include void split_str( std::string const &amp;str, const char delim, std::vector &amp;out ) { // create a stream from the string std::stringstream s(str); std::string s2; while (std:: getline (s, s2, delim) ) { out.push_back(s2); // store the string in s2 } } int main() { std:: string s2 = &apos;Learn How to split a string in C++&apos;; const char delim = &apos; &apos;; /* define the delimiter like space (&apos; &apos;), comma (,), hyphen (-), etc. */ std::cout &lt;&lt; &apos;Your given string is: &apos; &lt;&lt; s2; std::vector out; // store the string in vector split_str (s2, delim, out); // call function to split the string // use range based for loop for (const auto &amp;s2: out) { std::cout &lt;&lt; &apos;
&apos; &lt;&lt; s2; } return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Your given string is: Learn How to split a string in C++ Learn How to split a string in C++ </pre> <h3>Use find() and substr() function to split strings</h3> <p>Let&apos;s write a program to use find() function and substr() function to split given strings in C++.</p> <p> <strong>Program4.cpp</strong> </p> <pre> #include #include using namespace std; int main() { // given string with delimiter string given_str = &apos;How_to_split_a_string_using_find()_and_substr()_function_in_C++&apos;; string delim = &apos;_&apos;; // delimiter cout &lt;&lt; &apos; Your string with delimiter is: &apos; &lt;&lt; given_str &lt;&lt; endl; size_t pos = 0; string token1; // define a string variable // use find() function to get the position of the delimiters while (( pos = given_str.find (delim)) != std::string::npos) { token1 = given_str.substr(0, pos); // store the substring cout &lt;&lt; token1 &lt;&lt; endl; given_str.erase(0, pos + delim.length()); /* erase() function store the current positon and move to next token. */ } cout &lt;&lt; given_str &lt;&lt; endl; // it print last token of the string. } </pre> <p> <strong>Output</strong> </p> <pre> Your string with delimiter is: How_to_split_a_string_using_find()_and_substr()_function_in_C++ How to split a string using find() and substr() function in C++ </pre> <p>In the above program, we use a <strong>find()</strong> function inside the loop to repeatedly find the occurrence of the delimiter in the given string and then split it into tokens when the delimiter occurs. And the <strong>substr()</strong> function stores the sub-string to be printed. On the other hand, an erase() function stores the current position of the string and moves to the next token, and this process continues until we have got all the split strings.</p> <hr></=>

std::getline() 함수를 사용하여 문자열 분할

getline() 함수는 입력 스트림에서 문자열을 읽고 구분 기호 문자를 찾을 때까지 벡터 문자열에 넣는 데 사용되는 C++의 표준 라이브러리 함수입니다. 우리는 사용할 수 있습니다 표준::getline() 헤더 파일을 가져와서 작동합니다.

통사론

 getline(str, token, delim); 

여기에는 세 가지 매개변수가 있습니다.

str: str은 원래 문자열을 저장하는 변수입니다.

mysql과 같지 않음

토큰: 원본 문자열에서 추출된 문자열 토큰을 저장합니다.

공유하다: 문자열을 분할하는 데 사용되는 문자입니다. 예를 들어 쉼표(,), 공백( ), 하이픈(-) 등이 있습니다.

getline() 함수를 사용하여 문자열을 분할하는 프로그램

C++에서 getline() 함수를 사용하여 문자열을 분할하는 예를 살펴보겠습니다.

프로그램3.cpp

정수를 문자열로 변환 java
 #include #include #include #include using namespace std; int main() { string S, T; // declare string variables getline(cin, S); // use getline() function to read a line of string and store into S variable. stringstream X(S); // X is an object of stringstream that references the S string // use while loop to check the getline() function condition while (getline(X, T, &apos; &apos;)) { /* X represents to read the string from stringstream, T use for store the token string and, &apos; &apos; whitespace represents to split the string where whitespace is found. */ cout &lt;&lt; T &lt;&lt; endl; // print split string } return 0; } 

산출

 Welcome to the JavaTpoint and Learn C++ Programming Language. Welcome to the JavaTpoint and Learn C++ Programming Language. 

getline() 함수를 사용하여 주어진 문자열을 분할하는 프로그램

getline() 함수를 사용하여 C++에서 주어진 문자열을 분할하는 예를 고려해 보겠습니다.

프로그램4.cpp

 #include #include #include #include void split_str( std::string const &amp;str, const char delim, std::vector &amp;out ) { // create a stream from the string std::stringstream s(str); std::string s2; while (std:: getline (s, s2, delim) ) { out.push_back(s2); // store the string in s2 } } int main() { std:: string s2 = &apos;Learn How to split a string in C++&apos;; const char delim = &apos; &apos;; /* define the delimiter like space (&apos; &apos;), comma (,), hyphen (-), etc. */ std::cout &lt;&lt; &apos;Your given string is: &apos; &lt;&lt; s2; std::vector out; // store the string in vector split_str (s2, delim, out); // call function to split the string // use range based for loop for (const auto &amp;s2: out) { std::cout &lt;&lt; &apos;
&apos; &lt;&lt; s2; } return 0; } 

산출

 Your given string is: Learn How to split a string in C++ Learn How to split a string in C++ 

문자열을 분할하려면 find() 및 substr() 함수를 사용하십시오.

C++에서 주어진 문자열을 분할하기 위해 find() 함수와 substr() 함수를 사용하는 프로그램을 작성해 보겠습니다.

프로그램4.cpp

 #include #include using namespace std; int main() { // given string with delimiter string given_str = &apos;How_to_split_a_string_using_find()_and_substr()_function_in_C++&apos;; string delim = &apos;_&apos;; // delimiter cout &lt;&lt; &apos; Your string with delimiter is: &apos; &lt;&lt; given_str &lt;&lt; endl; size_t pos = 0; string token1; // define a string variable // use find() function to get the position of the delimiters while (( pos = given_str.find (delim)) != std::string::npos) { token1 = given_str.substr(0, pos); // store the substring cout &lt;&lt; token1 &lt;&lt; endl; given_str.erase(0, pos + delim.length()); /* erase() function store the current positon and move to next token. */ } cout &lt;&lt; given_str &lt;&lt; endl; // it print last token of the string. } 

산출

 Your string with delimiter is: How_to_split_a_string_using_find()_and_substr()_function_in_C++ How to split a string using find() and substr() function in C++ 

위 프로그램에서는 찾다() 루프 내에서 함수를 사용하여 주어진 문자열에서 구분 기호의 발생을 반복적으로 찾은 다음 구분 기호가 발생할 때 이를 토큰으로 분할합니다. 그리고 하위 문자열() 함수는 인쇄할 하위 문자열을 저장합니다. 반면, erasure() 함수는 문자열의 현재 위치를 저장하고 다음 토큰으로 이동하며, 이 프로세스는 분할된 문자열을 모두 얻을 때까지 계속됩니다.