- How to Split a String in C++? 6 Easy Methods (with code)
- 6 Methods to Split a String in C++
- 1) Using Temporary String
- 2) Using stringstream API of C++
- 3) Using strtok() Function
- 4) Using Custom split() Function
- 5) Using std::getline() Function
- 6) Using find(), substr() and erase() Functions
- Conclusion
- Split String by Space in C++
- Use std::string::find and std::string::substr Functions to Split String by Space in C++
- Use std::istringstream and std::copy to Split String by Space in C++
- Use std::getline and erase-remove Idiom to Split String by Space in C++
- Related Article — C++ String
How to Split a String in C++? 6 Easy Methods (with code)
Many programming languages provide the split function to separate the string into words. But does C++ have a split function? There is no in-built function like split() in C++. So, how do you split a string in C++? We have numerous ways to achieve this functionality. Let’s learn about all of them!
6 Methods to Split a String in C++
Here is the list of those methods which you can use to split a string into words using your own delimiter function:
- Using Temporary String
- Using stringstream API of C++
- Using strtok() Function
- Using Custom split() Function
- Using std::getline() Function
- Using find(), substr() and erase() Functions
Now, to split a string we must specify on what basis we are going to do it, here comes the delimiter. So, splitting strings is only possible with specific delimiters such as white space( ), comma(,), hyphen(-), and so on, resulting in individual words.
1) Using Temporary String
In this example, we are first taking input from the user using getline() function, and the separator variable is used as a delimiter to separate the string using commas.
Then, we are iterating to the end of the string, if we do not find our space delimiter, then we will continue adding chars to my temp string and if in between we found our delimiter then, just print that string and make it empty as shown in the below example:
// Welcome to Favtutor #include #include using namespace std; int main() < char arr[100]; // Input using the getline function. cin.getline(arr, 100); char separator = ' '; int i = 0; // Temporary string used to split the string. string s; while (arr[i] != '\0') < if (arr[i] != separator) < // Append the char to the temp string. s += arr[i]; > else < cout s endl; s.clear(); > i++; > // Output the last stored word. cout s endl; >
I love to read articles on the scaler topics.
I love to read articles on the scaler topics.
2) Using stringstream API of C++
You need to know about stringstream first.
We use cin stream to take input from the user, similarly, we first initialize the stringstream’s object and take the input in it using »
The most commonly used stringstream operators are as follows:
Note: Tokenizing a string means splitting it with respect to a delimiter.
Syntax of stringstream object:
stringstream obj_name(string string_name);
In this method, we will first create a stringstream object which will take the string and split it into words automatically. To read those words we will create a variable word and we will read all the words till my stringstream object exhaust.
// Welcome to Favtutor #include using namespace std; int main() < string s = "I love to read articles on Favtutor."; // Takes only space separated C++ strings. stringstream ss(s); string word; while (ss >> word) < // Extract word from the stream. cout word endl; > cout endl; return 0; >
I love to read articles on Favtutor.
3) Using strtok() Function
The strtok() function splits the string into tokens based on the delimiter passed. The strtok() function modifies the original string on each call by inserting the NULL character (\0) at the delimiter position. This allows it to track the status of the token easily.
char *ptr = strtok (string, delimiter);
Here, the string is the given which we want to split, delimiter is the parameter or character based on which we separate the string. It returns a pointer to the next character tokens. It initially points to the first token of the strings.
In this method, we are first taking string as input using getline() function and then creating a pointer of type char and using strtok() function with space as a delimiter, it will give us each word. For that, we run a loop until the char pointer is not equal to NULL . In each iteration, we print the pointer.
//Welcome to Favtutor #include #include using namespace std; int main() < char s[100]; cin.getline(s, 100); // Pointer to point the word returned by the strtok() function. char * p; // Here, the delimiter is white space. p = strtok(s, " "); while (p != NULL) < cout p endl; p = strtok(NULL, " "); > >
I love to read articles on Favtutor.
I love to read articles on Favtutor.
4) Using Custom split() Function
In this method, we are using for loop to iterate over the entire string until we find our delimiter. If found, then we will append up to that string into a vector of temp string and update the startIndex and endIndex accordingly. Here, we are defining our own custom function to split a string in C++.
// Welcome to favtutor #include #include using namespace std; vector string > strings; // Create custom split() function. void customSplit(string str, char separator) < int startIndex = 0, endIndex = 0; for (int i = 0; i str.size(); i++) < // If we reached the end of the word or the end of the input. if (str[i] == separator || i == str.size()) < endIndex = i; string temp; temp.append(str, startIndex, endIndex - startIndex); strings.push_back(temp); startIndex = endIndex + 1; > > > int main() < string str = "I love to read articles on Favtutor."; // Space is used as a separator. char separator = ' '; customSplit(str, separator); cout <" The split string is: "for (auto it: strings) < coutreturn 0; >
The split string is: I love to read articles on Favtutor.
5) Using std::getline() Function
Just as we take the input from the user using getline() function, similarly we will take the input into the sringstream using getline() function.
getline(string, token, delimiter);
Here, the token saves the extracted string tokens from the original string. Below is the C++ program implementation:
// Welcome to favtutor #include using namespace std; int main() < string s, str; s = "I love to read articles on Favtutor."; // ss is an object of stringstream that references the S string. stringstream ss(s); // Use while loop to check the getline() function condition. while (getline(ss, str, ' ')) // `str` is used to store the token string while ' ' whitespace is used as the delimiter. cout str endl; return 0; >
I love to read articles on Favtutor.
6) Using find(), substr() and erase() Functions
In this method, we will use the find(), substr(), and erase() function to split the given string using our delimiter.
string substr (size_t position, size_t length);
Note: The substr() returns a string object and size_t is an unsigned integer type. Below is the C++ program implementation :
// Welcome to Favtutor #include using namespace std; void find_str(string s, string del) < // Use find function to find 1st position of delimiter. int end = s.find(del); while (end != -1) < // Loop until no delimiter is left in the string. cout s.substr(0, end) endl; s.erase(s.begin(), s.begin() + end + 1); end = s.find(del); > cout s.substr(0, end); > int main() < string a = "I love to read articles on Favtutor."; // Here, the delimiter is white space. string del = " "; find_str(a, del); return 0; >
I love to read articles on Favtutor.
Conclusion
In this article, we learned about the various methods involved to take words out of the given string or to split a string based on the delimiter passed. In competitive programming, you will find most of the time the use of this operation accordingly. Now you know how to split a string in C++.
Congratulations on getting this far! Now give yourself a pat on the back. Good job!
Split String by Space in C++
- Use std::string::find and std::string::substr Functions to Split String by Space in C++
- Use std::istringstream and std::copy to Split String by Space in C++
- Use std::getline and erase-remove Idiom to Split String by Space in C++
This article will demonstrate multiple methods about how to split string by space delimiter in C++.
Use std::string::find and std::string::substr Functions to Split String by Space in C++
find and substr are std::string builtin functions that can be utilized to split string by any delimiter specified by the string value or a single character. The find function takes a string argument and returns the position on which the given substring starts; otherwise, if not found, string::npos is returned. Thus, we iterate in the while loop until the find function returns npos . Meanwhile, the substr method can be utilized to access the part of the string before the delimiter, which in this case is a single space character and store into a vector for later usage. After that, we call the erase function to remove the first sequence, including the delimiter, at which point a new iteration may proceed to repeat the operations.
#include #include #include #include #include #include using std::cout; using std::cin; using std::endl; using std::string; using std::vector; using std::istringstream; using std::stringstream; int main() string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " "Sed laoreet sem leo, in posuere orci elementum."; string space_delimiter = " "; vectorstring> words<>; size_t pos = 0; while ((pos = text.find(space_delimiter)) != string::npos) words.push_back(text.substr(0, pos)); text.erase(0, pos + space_delimiter.length()); > for (const auto &str : words) cout > return EXIT_SUCCESS; >
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed laoreet sem leo, in posuere orci
Use std::istringstream and std::copy to Split String by Space in C++
Alternatively, we can reimplement the code using the istringstream class, which provides input/output operations for string based streams. Once we initialize the istringstream object with the string value that needs to be split, then the std::copy algorithm can be called to output each space-separated string value to the cout stream. Note that this method only supports the space delimiter splitting because that’s what the implementation of the istringstream class provides.
#include #include #include #include #include #include using std::cout; using std::cin; using std::endl; using std::string; using std::vector; using std::istringstream; using std::stringstream; int main() string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " "Sed laoreet sem leo, in posuere orci elementum."; vectorstring> words<>; istringstream iss(text); copy(std::istream_iteratorstring>(iss), std::istream_iteratorstring>(), std::ostream_iteratorstring>(cout, "\n")); return EXIT_SUCCESS; >
Use std::getline and erase-remove Idiom to Split String by Space in C++
One downside of the previous solution is the punctuation symbols stored with parsed words. It may be solved with the erase-remove idiom, which is essentially a conditional removal operation for the given range. In this case, we call this method on each word retrieved by std::getline to trim all punctuation symbols in it. Note that the ispunct function object is passed as the third argument to the remove_if algorithm to check for the punctuation characters.
#include #include #include #include #include #include using std::cout; using std::cin; using std::endl; using std::string; using std::vector; using std::istringstream; using std::stringstream; int main() string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " "Sed laoreet sem leo, in posuere orci elementum."; char space_char = ' '; vectorstring> words<>; stringstream sstream(text); string word; while (std::getline(sstream, word, space_char)) word.erase(std::remove_if(word.begin(), word.end(), ispunct), word.end()); words.push_back(word); > for (const auto &str : words) cout > return EXIT_SUCCESS; >
Lorem ipsum dolor sit amet consectetur adipiscing elit Sed laoreet sem leo in posuere orci elementum
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.