If you have completed the Basics of C++ Programming Language, then you might have gone through the Strings Concept in C++. If you are confident in C++ Strings, then we can move ahead into some Advanced String Concepts. “Split Strings In C++” is one such advanced string concept that we have to learn.
The short answer: C++ has no built-in split() function. To split a string by a delimiter, put the string into a stringstream and read it piece by piece with getline().
stringstream ss("red,green,blue");
string part;
while (getline(ss, part, ','))
cout << part << endl; // red, then green, then blue
Any single statement can be divided into each word using the C++ String Splitting Method. In this article, we will discuss different methods to split a single statement into different words using the C++ Language. Every program below was compiled with g++ and run before we put it here, and the output under each one is copied from that run. So, let us start our discussion.
Summary Or Key Highlights:
- Split String in C++ is the method by which we can extract different words from any statement.
- We need to Split the Strings in C++ when we are dealing with any Textual Dataset.
- To Split the strings in C++, there are 7 different methods that we can use. Five of them work in any C++ version, one needs C++11, and one needs C++20.
- The methods do not agree on what to do with empty parts, like the gap in "a,,b". We have tested all of them on the same input so you can see the difference.
- While splitting the strings in C++, we have to keep in mind some Memory Implications.
- What Is String Splitting In C++?
- Which Method Should You Use?
- Methods to Split Strings in C++
- Splitting By A Whole Word Or Symbol Like " -> "
- Splitting By Several Delimiters At Once
- What Happens With Empty Parts?
- Splitting And Converting To Numbers
- Splitting A String Into Characters
- Comparison Table and Speed Test
- Common Mistakes
- Frequently Asked Questions
What Is String Splitting In C++ Language?
Splitting strings is a common requirement when dealing with textual data. It allows us to extract meaningful information, manipulate data effectively, and process inputs from different sources. Consider scenarios such as extracting words from a sentence, parsing data from a CSV file, or simply tokenizing the user input.
Tokenizing is the process of breaking down user-provided input into smaller units called tokens, which are meaningful components of the input that can be processed or analyzed individually.
The character or the sequence of characters that we use to mark the boundaries between different parts of the string is called a delimiter. The substrings on either part of a delimiter are considered two different tokens. Common delimiters are commas, spaces, colons, etc.
For example, if the string is "red,green,blue" and the delimiter is a comma, the tokens are "red", "green", and "blue". In most programs, we store these tokens in a vector so we can use them later. If vectors are new to you, our guide on how to initialize a vector in C++ will help.
Which Method Should You Use?
If you are in a hurry, this small table will point you to the right method. The details of each one are discussed below.
| Your Situation | Method To Use |
|---|---|
| Words separated by spaces | stringstream with >> |
| One delimiter character, like a comma (CSV line) | stringstream with getline() |
| You must keep every empty field, even the last one | find() and substr() |
| The delimiter is longer than one character, like " -> " | find() and substr() with a string delimiter |
| Several different delimiters in the same text | find_first_of() or regex |
| Your course uses C++20 | views::split |
| You are working with C-style char arrays | strtok() |
What are the Methods to Split Strings in C++? Read Below
Although C++ does not have a built-in ‘split()’ function like Java or Python, it offers a plethora of alternatives to achieve the same outcome.
One note before we start. In the programs below, we include the exact header files that each method needs, like <sstream> and <vector>. You may have seen #include <bits/stdc++.h> in other tutorials. It is a shortcut that is not part of standard C++. It comes with the GCC library, so it can fail on Visual Studio and on a Mac, so it is better not to depend on it in your assignments.
1. Using only stringstream:
A stream in programming refers to a continuous flow of data elements that can be read from or written to by the computer. It is an abstraction that represents a flow of data, similar to a stream of water flowing continuously, upon which we can perform operations in a sequential manner.
The stringstream class in C++ is part of the <sstream> header and provides us with a convenient way to treat strings as input/output streams. It allows us to read data from a string and write data to a string as if they were input and output streams, respectively.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string zap = "Alex 25 Writer";
stringstream sg(zap); // Using Stringstream With String
string a, b;
int c;
sg >> a >> c >> b; // Splitting All The Strings
cout << "Split Strings With Stringstream: " << endl;
cout << a << "\n" << c << "\n" << b << endl;
return 0;
}
Steps Of The Program:
- To use stringstream, we create an object of the stringstream class and initialize it with a string.
- This creates a stream-like object that can be used to perform operations on the string.
- The ‘>>’ operator is used to extract the individual data elements from a stringstream separated by a space. It treats spaces, tabs, and newlines as the delimiter.
- Now, we can see that our input had elements of different data types, which were read efficiently into their respective data types by using the ‘>>’ operator.
- Thus the stringstream provides an efficient method to read data.
Output:
Split Strings With Stringstream: Alex 25 Writer
The program above works when we know that the sentence has exactly three parts. Most of the time, we do not know how many words there are. In that case, we put the ‘>>’ operator inside a While Loop and collect the words in a vector.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string zap = " We love C++ strings ";
stringstream sg(zap);
string word;
vector<string> words;
while (sg >> word) // Runs Until No Word Is Left
words.push_back(word);
cout << "Total Words: " << words.size() << endl;
for (auto& w : words)
cout << "[" << w << "]" << endl;
return 0;
}
Output:
Total Words: 4 [We] [love] [C++] [strings]
Look at the input string closely. It has extra spaces at the start, at the end, and between the words. The ‘>>’ operator skips all of them and gives us only the 4 real words. This is why it is the safest method for sentences typed by a user.
2. Using StringStream with getline() function and Delimiter
The ‘getline()’ function is a versatile function that is used to extract data from a stream, such as a stringstream or cin. Its basic syntax is as follows:
SYNTAX: getline(stream, str, delimiter)
It reads the characters from the ‘stream’ until it encounters the ‘delimiter’ specified by the user. If we do not give any delimiter, it stops at the newline character (‘\n’). It then stores the extracted characters into the string specified by the user (‘str’).
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string i, char d) // Creating Vector Function For Delimiter
{
stringstream sg(i); // Converting String To String Stream
string t;
vector<string> ts;
while (getline(sg, t, d)) // Checking The String Based On Delimiter
ts.push_back(t);
return ts;
}
int main()
{
string zap = "CodingZap Is My Love";
vector<string> ts = split(zap, ' ');
cout << "Split Strings With Delimiter: " << endl;
for (auto& t : ts) // Printing The String
cout << t << "\n";
return 0;
}
Steps Of The Program:
- At first, we will make the Split() Function that will take the String and the Delimiter.
- Now, the Stringstream will be developed that will take the Input String.
- Later, a While Loop will be executed that will read the string up to each Delimiter and pick up the Word before it.
- That word will be inserted into the newly created vector that will be shared with the Main Function.
- In the Main Function, we will call the User-defined Function and these whole tasks will be executed.
Output:
Split Strings With Delimiter: CodingZap Is My Love
Keep one limit in mind. The delimiter in getline() is a single character, written in single quotes like ' ' or ','. We cannot pass a word or two characters to it.
3. Using find() and substr() functions:
We can also use the find() and substr() functions in conjunction to extract data from our string and split it around any delimiter of choice.
The find() function, a function of the std::string class, is used to find a specified character or substring in any given string and returns the first occurrence of the substring after the starting position if found, else it returns string::npos to depict that the substring is not found.
SYNTAX: find(substring, pos);
The substr() function is also a member function of the std::string class and is used to extract a substring from a given string. It takes the start index and the length of the substring to be extracted as its parameters and returns the required substring.
SYNTAX: substr(pos, len);
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string i, char d) // Method To Split String Using Find And Substr
{
vector<string> ts; // Creating The Vector
size_t s = 0; // Start Index Of First Token
size_t e = i.find(d); // First Occurrence Index Of Delimiter Using Find()
while (e != string::npos) // Extracting Tokens Based On Delimiter
{
ts.push_back(i.substr(s, e - s)); // Pushing The Substring
s = e + 1;
e = i.find(d, s);
}
// Pushing The last Token Using Substr()
ts.push_back(i.substr(s));
return ts;
}
int main()
{
string zap = "CodingZap-Is-The-Best-Website";
vector<string> ts = split(zap, '-'); // Calling The Function
cout << "Split Strings Using Find And Substr: " << endl;
for (auto& t : ts) // Printing The Strings
cout << t << endl;
return 0;
}
Steps Of The Program:
- First, the Split() Function will be developed that will take the String and the Delimiter.
- Now, we will use the Find() Function to get the Index of the first Delimiter.
- Later, a While Loop will be executed that will check from the First Delimiter Index to the end of the string.
- In between that, each word will be picked up and will be inserted into the Vector “TS”.
- This Vector will be shared with the Main Function to print the result.
- In the Main Function, we will take a sentence where words are separated using the "-" Delimiter.
- We will call that User-defined Function with the String Name and the Delimiter.
Output:
Split Strings Using Find And Substr: CodingZap Is The Best Website
Notice that the index variables ‘s’ and ‘e’ are of type size_t, not int. The find() function returns a size_t, and string::npos is the largest value a size_t can hold. If we store the result in an int and compare it with npos, the compiler gives a "comparison of integer expressions of different signedness" warning, and on very large strings the result can be wrong.
4. Using strtok() function:
The strtok() function in C++ is a string tokenization function that is part of the C standard library. It is used to split a string into a sequence of tokens based on a specified set of delimiter characters.
SYNTAX: strtok(str, delimiter);
Here, both the string ‘str’ and the delimiter are C-styled strings. String ‘str’ is the string that needs to be split, and the delimiter defines the set boundaries. The function strtok() returns a pointer to the first token found in the string. If no token is found, it returns a null pointer.
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string i, const char* d) // Function To Split String Using Strtok
{
vector<string> ts; // Creating A Vector For Strings
// Getting The First Element Of String Using Strtok
// i Is Our Own Copy, So Strtok Is Free To Change It
char* t = strtok(&i[0], d);
while (t != NULL) // We Are Getting Tokens Using Strtok
{
ts.push_back(string(t));
t = strtok(NULL, d);
}
return ts;
}
int main()
{
string zap = "Please$Use$The$CodingZap$Website";
vector<string> ts = split(zap, "$"); // Calling The Function With Double Quote
cout << "Split Strings using Strtok: " << endl;
for (auto& t : ts) // Printing The Strings
cout << t << endl;
return 0;
}
Steps Of The Program:
- In this case, as well, the Split() Function will be created where the String and the Delimiter Pointer will be shared.
- Now, a New Vector “TS” will be created that will take the Words from the Sentence.
- Now, the first element of the String will be taken using the Strtok() Function.
- Later, the While Loop will be executed and will check the sentence till the Character Pointer becomes NULL at the end of the sentence.
- After each Delimiter, the String Word will be picked and inserted into the Vector.
- In the end, the Vector will be shared with the Main Function for printing.
- In the Main Function, a Sentence will be taken where words are separated using the “$” Symbol.
- We will call the User-defined Function along with the String Name and the “$” Delimiter.
Output:
Split Strings using Strtok: Please Use The CodingZap Website
It’s important to note that strtok() works on C-styled strings, not on C++ string objects. It modifies the string we give it by writing null terminators over the delimiters. That is why our function takes the string by value. It gets its own copy, so the original string in the Main Function stays safe. Additionally, strtok() is not thread-safe, meaning it can have unexpected behavior in a multi-threaded environment.
Two more things surprise students with strtok(). First, the second argument is a set of characters. If we pass ",;" it will split on a comma or a semicolon, not on the two characters together. Second, we should never pass a string literal to it. A literal sits in read-only memory, so when strtok() tries to write into it, the program usually crashes with a Segmentation fault. We tried it with char* text = "a,b,c";. The compiler gave only a warning for that line, and the program crashed when it ran.
Crashes like this are hard to trace, because the line that crashes is often not the line that has the mistake. If your program is crashing and you cannot find the reason, a C++ tutor from our team can go through the code with you.
5. Creating Your Custom Function:
In addition to the provided inbuilt methods, we can also create our custom algorithm to split strings in C++. There can be many ways to split strings using a custom function. One of them is as follows:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(const string& i, char d) // Splitting String Using Custom Function
{
vector<string> ts;
string t; // Temporary String To Hold Characters
for (char c : i) { // For Loop To Iterate Through Characters
if (c != d) {
t += c; // Appending The Character To String
} else {
ts.push_back(t); // Adding The Completed Token
t.clear();
}
}
// Adding The last Token Of The String
if (!t.empty()) {
ts.push_back(t);
}
return ts; // Returning The Vector
}
int main()
{
string zap = "The Best Website Is CodingZap";
vector<string> ts = split(zap, ' '); // Calling The Function
cout << "Split Strings Using Custom Function: " << endl;
for (auto& t : ts) // Printing The Strings
cout << t << endl;
return 0;
}
Steps Of The Program:
- Here, we iterate through each character of the input string.
- If a character is not equal to the delimiter, we append it to the temp string. This step allows us to construct each token by progressively adding characters.
- Upon encountering a delimiter character, we consider the current token complete.
- We then add the content of the temp string to the tokens vector.
- Following that, we clear the temp string in preparation for the next token.
- After processing all the characters in the input string, if there is any remaining content in the temp string, we include it as the last token, provided it is not empty.
Output:
Split Strings Using Custom Function: The Best Website Is CodingZap
Some courses ask for this version on purpose, with an instruction like "do not use stringstream or strtok." So, it is worth practicing even if you never use it in a real project.
6. Using Regex (Regular Expressions):
From C++11, the <regex> header gives us one more way. Here, the delimiter is not a fixed character. It is a pattern. This is helpful when the text is messy, for example, when the words are separated by a comma in one place, a semicolon in another, and three spaces somewhere else.
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
vector<string> split(const string& i, const string& pattern) // Splitting String Using Regex
{
regex re(pattern);
// The -1 Means "Give Me The Parts Between The Matches"
sregex_token_iterator first(i.begin(), i.end(), re, -1);
sregex_token_iterator last;
return vector<string>(first, last);
}
int main()
{
string zap = "apple, banana;cherry mango";
// One Or More Commas, Semicolons Or Spaces In A Row Count As One Delimiter
vector<string> ts = split(zap, "[,; ]+");
cout << "Split Strings Using Regex: " << endl;
for (auto& t : ts) // Printing The Strings
cout << t << endl;
return 0;
}
Steps Of The Program:
- We create a regex object from the pattern. The pattern "[,; ]+" means one or more commas, semicolons, or spaces.
- The sregex_token_iterator walks through the string and finds every place where the pattern matches.
- The last argument, -1, tells it to give us the text between the matches, which are our tokens.
- We build the vector directly from the two iterators and return it.
Output:
Split Strings Using Regex: apple banana cherry mango
Regex is the most flexible method, but it is also the slowest by a big margin, as you will see in the speed test below. Use it when the delimiters are irregular, not for a simple comma.
7. Using views::split (C++20):
If you have a recent compiler that supports C++20, the <ranges> header finally brings something close to a real split function. We do not need a stream or any index calculation.
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
int main()
{
string zap = "2026-10-03";
vector<string> ts;
for (auto part : views::split(zap, '-')) // Each Part Is A Small Range Of Characters
ts.push_back(string(part.begin(), part.end()));
cout << "Split Strings Using Ranges: " << endl;
for (auto& t : ts) // Printing The Strings
cout << t << endl;
return 0;
}
Steps Of The Program:
- The views::split() function takes the string and the delimiter. It does not create the tokens immediately. It gives them one by one as the loop asks for them.
- Each ‘part’ is a small range of characters, not a string. So, we build a string from its begin() and end().
- We push each string into the vector and print it.
Output:
Split Strings Using Ranges: 2026 10 03
To compile this program with g++, we have to add the -std=c++20 flag. If your course is fixed on C++11, C++14, or C++17, this method will not compile, and you should use one of the first five methods.
One trap to know about: if the delimiter is longer than one character, do not pass it in plain double quotes. Writing views::split(zap, " -> ") finds nothing, because the hidden null character at the end of the literal becomes part of the delimiter. Wrap it as string_view(" -> ") and it works.
How To Split A String By A Whole Word Or Symbol Like " -> "?
So far, every delimiter was a single character. But sometimes the delimiter is longer, like ", " (comma and space), "::" or " -> ". The getline() function cannot do this, and strtok() will treat each character separately. The find() and substr() method handles it with one small change.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(const string& i, const string& d) // Delimiter Is A Whole String
{
vector<string> ts;
size_t s = 0;
size_t e = i.find(d);
while (e != string::npos)
{
ts.push_back(i.substr(s, e - s));
s = e + d.length(); // Jump Over The Whole Delimiter, Not Just One Character
e = i.find(d, s);
}
ts.push_back(i.substr(s));
return ts;
}
int main()
{
string zap = "Boston -> Chicago -> Denver -> Seattle";
vector<string> ts = split(zap, " -> ");
for (auto& t : ts)
cout << "[" << t << "]" << endl;
return 0;
}
Output:
[Boston] [Chicago] [Denver] [Seattle]
The only difference from Method 3 is the line s = e + d.length();. Earlier, we moved ahead by 1 because the delimiter was one character. Now, we move ahead by the full length of the delimiter. If we forget this and write e + 1, pieces of the delimiter will show up at the start of every token.
How To Split A String By Several Delimiters At Once?
In a normal English sentence, words are separated by spaces, commas, question marks, and more. To split on any of them, we can use find_first_of() and find_first_not_of(). The first one finds the next delimiter. The second one finds the next character that is not a delimiter.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(const string& i, const string& delims) // Any Character In delims Is A Delimiter
{
vector<string> ts;
size_t s = i.find_first_not_of(delims); // Skip Delimiters At The Start
while (s != string::npos)
{
size_t e = i.find_first_of(delims, s); // Where This Token Ends
ts.push_back(i.substr(s, e - s));
s = i.find_first_not_of(delims, e); // Where The Next Token Starts
}
return ts;
}
int main()
{
string zap = "Hello, world! How are you?";
vector<string> ts = split(zap, " ,!?");
for (auto& t : ts)
cout << "[" << t << "]" << endl;
return 0;
}
Output:
[Hello] [world] [How] [are] [you]
The comma and the space after "Hello" come one after another, but we did not get an empty token between them. The find_first_not_of() call jumps over all the delimiters in a row. This makes it a good choice for counting words in a sentence.
What Happens With Empty Parts Like "a,,b,"?
This part is easy to miss, and it can quietly break a program that looked correct. Suppose a CSV line has a missing value, or the line ends with a comma. Should we get an empty token or not? The methods above do not give the same answer. We ran all of them on the same input, "a,,b,", and printed each token inside square brackets.
Input: "a,,b," getline 3 tokens: [a][][b] find + substr 4 tokens: [a][][b][] strtok 2 tokens: [a][b] custom function 3 tokens: [a][][b] regex "," 3 tokens: [a][][b] views::split 4 tokens: [a][][b][]
From the above output, we can see three different behaviors:
- find() with substr() and views::split keep everything. We get 4 tokens, including the empty one in the middle and the empty one at the end.
- getline(), our custom function, and regex keep the empty token in the middle but drop the one at the end. We get 3 tokens.
- strtok() throws away all the empty tokens. We get only 2.
So, which one is correct? It depends on the task. If you are reading a CSV file with a fixed number of columns, you need all 4, or your columns will shift. If you are counting words, you want none of the empty ones. Before you choose a method, check what your assignment expects for this case, and test it with an input like the one above.
How To Split A String And Convert The Parts To Numbers?
Very often, the tokens are numbers stored as text, like a line of scores "85,92,78". After splitting, we convert each token using the stoi() function. But if a token is not a number, or the number is too big for an int, stoi() throws an exception, and the program stops if we do not catch it.
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
using namespace std;
int main()
{
string line = "85,92,abc,99999999999,78";
stringstream sg(line);
string t;
int total = 0;
while (getline(sg, t, ','))
{
try {
total += stoi(t); // Converting The Token To A Number
} catch (const invalid_argument&) {
cout << "Skipping \"" << t << "\" because it is not a number" << endl;
} catch (const out_of_range&) {
cout << "Skipping \"" << t << "\" because it is too big for an int" << endl;
}
}
cout << "Total: " << total << endl;
return 0;
}
Output:
Skipping "abc" because it is not a number Skipping "99999999999" because it is too big for an int Total: 255
The try-catch blocks let the program skip the bad values and continue with the rest. One thing stoi() will not catch for us: a token like "12abc" is quietly read as 12, because stoi() stops at the first character that is not a digit. For decimal numbers, use stod() instead of stoi(). If errors like these are new to you, our guide on common C++ errors covers the ones you are most likely to run into.
How To Split A String Into Individual Characters?
Sometimes, "split a string by character" means something else: breaking a word into its letters. For this, we do not need any of the methods above. A C++ string is already a sequence of characters, so a simple loop is enough.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string zap = "Hello";
// A String Is Already A Sequence Of Characters
for (char c : zap)
cout << c << " ";
cout << endl;
// If You Need Them Stored Separately
vector<char> letters(zap.begin(), zap.end());
cout << "Total Characters: " << letters.size() << endl;
return 0;
}
Output:
H e l l o Total Characters: 5
Comparison Table On String Splitting Methods:
Now, after discussing all of the methods to Split String in C++, let us get some more details on them by making a Comparison Table. Here, we will make the Comparison Table based on the categories like Complexity, Delimiter Support, etc.
Let us have a look at the following Comparison Table to learn more about it.
| Categories | Stringstream (SS) | SS With Delimiter | Find() And Substr() | Strtok() | Custom Function | Regex | views::split |
|---|---|---|---|---|---|---|---|
| Complexity | Easy | Easy | Moderate | Moderate | Moderate | Hard | Moderate |
| Available Since | C++98 | C++98 | C++98 | C++98 (from C) | C++98 | C++11 | C++20 |
| Original String Modification | No | No | No | Yes | Depends on Implementation | No | No |
| Delimiter It Accepts | Spaces, tabs, newlines only | One character | One character or a whole string | Any character from a set | Whatever we code | A pattern | One character, or a string_view |
| Empty Tokens | Skipped | Kept, except the last | All kept | All skipped | Kept, except the last (in our version) | Kept, except the last | All kept |
One note on the second row: the functions themselves are old, but our example programs use auto and the range-based for loop to print the result, so compile them as C++11 or later.
Which Method Is The Fastest? Our Speed Test
Instead of guessing, we measured it. We built one long string with 1,000,000 tokens separated by commas (about 7.9 million characters), split it with each method, and took the best time out of 5 runs. The program was compiled with g++ 13 using the -O2 option.
| Method | Tokens Found | Time |
|---|---|---|
| Stringstream with getline() | 1,000,000 | 43 ms |
| find() and substr() | 1,000,000 | 36 ms |
| strtok() | 1,000,000 | 54 ms |
| Custom function | 1,000,000 | 38 ms |
| Regex | 1,000,000 | 329 ms |
| views::split (C++20) | 1,000,000 | 25 ms |
| find() returning string_view (C++17) | 1,000,000 | 8 ms |
These numbers are from one machine and short tokens of 7 characters or less, so yours will be different. But the pattern is what matters:
- The first four methods in the table are all close to each other. For an assignment, you will never feel the difference between them.
- Regex is many times slower than the rest. It is fine for a line of text, but not for a large file.
- The last row is a small change to Method 3. It returns
string_viewobjects instead of strings (C++17). A string_view does not copy the characters. It only points into the original string, which is why it is so fast. The catch is that the original string must stay alive as long as we are using the tokens.
Every method reads each character once, so the time complexity is roughly O(n) for all of them, where n is the length of the string. The extra memory is also O(n), because the tokens together are about as long as the input.
What Is The Importance Of String Splitting In C++?
If you are thinking that the String Splitting in C++ is a useless concept and you are learning it unnecessarily, then you are thinking wrong. There is a huge importance of String Splitting across different fields. In this section, we are going to check that.
Let us have a look at the following list where the importance of String Splitting is discussed.
- For Data Parsing and Extracting Useful Data, the String Splitting Concept should be used. Reading a CSV file line by line is the most common example.
- For Text Manipulation, the use of the String Splitting Process is needed.
- String Splitting can sometimes be used for Handling User Inputs and Commands. For example, breaking "add 5 10" into a command and its two numbers.
- To do Efficient Searching and Pattern Matching, the String Splitting Process is used.
- To do a String Comparison easily, sometimes, the String Splitting Process is used.
What Are Some Common Mistakes While Splitting Strings In C++?
A few mistakes come up again and again with this topic. Let us have a look at them so you can avoid them.
- Forgetting the last token. In the find() and substr() method, the loop ends when no more delimiter is found. But the text after the last delimiter is still there. If we leave out the final
push_back(i.substr(s)), the last word goes missing. - Using double quotes for the getline() delimiter. Writing
getline(sg, t, ",")gives a compile error. The delimiter must be a char in single quotes, like ','. - Storing the result of find() in an int. As discussed in Method 3, use size_t when you compare with string::npos.
- Passing a string literal or a const string to strtok(). It needs memory it is allowed to change.
- Not thinking about empty tokens. An input like "a,,b," gives 2, 3, or 4 tokens depending on the method. Test your program with such an input before you submit it.
- Calling stoi() on a token without checking it. One bad value in the input will stop the whole program unless we catch the exception.
What Are Some Best Practices To Split The Strings In C++?
We hope whatever we have discussed till now, has become clear to you. Now, as we are moving towards the end of the journey, let us conclude it by shedding some light on the Best Practices to Split the Strings in C++.
Let us have a look at the following list to know more about those tips.
- We should prefer a method that lets us pass the Delimiter as an Argument, so the same function works for commas, spaces, and anything else.
- We have to prefer the method that doesn’t modify the Original String in C++.
- If we are using any Large Strings, we should avoid the methods that create unnecessary copies. Passing the string as
const string&instead ofstringis the easiest way to save one copy. - If we are using any Custom Function, we should optimize it to reduce the Memory Consumption.
- We should write the split logic once as a function and reuse it, rather than repeating the loop in every part of the program.
Conclusion:
In the end, we can say it is very important to know about the “Split Strings In C++”.
However, we will advise you to clear the basics of C++ Strings before starting the String Splitting Concept. If the Basic String Concept is not clear to you, then you are not going to understand the String Split Concept. So, you should first clear your basic understanding of Strings.
Takeaways:
- For most assignments, the best way to Split the String in C++ will be by using the Stringstream Concept.
- With the Stringstream, we can use the Delimiter Argument of getline() for better String Splitting.
- If we are using Find(), Substr(), or Strtok(), we have to write a little more code, but we get more control over the delimiter.
- The methods treat empty tokens differently, so we should always test with an input like "a,,b,".
- Delimiter Type, Memory Efficiency, Compatibility, etc. are some points that we keep in mind while splitting the string.
Frequently Asked Questions:
1) Is there a split() function in C++?
No. The C++ standard library has no split() function for strings like Python or Java have. The closest thing is views::split in C++20. In older versions, we use a stringstream with getline(), or find() with substr().
2) What is the easiest way to split a string by space in C++?
Put the string in a stringstream and read it with the >> operator inside a while loop. It skips extra spaces, tabs, and newlines automatically, so we get only the real words.
3) How do I split a string by comma in C++?
Use a stringstream with getline(stream, token, ','). Each call reads the text up to the next comma. If the line can end with a comma and you need that last empty field, use find() with substr() instead.
4) How do I split a string into an array in C++?
Split it into a vector of strings, as shown in the programs above. A vector grows on its own, so we do not need to know the number of tokens in advance. If the assignment asks for a plain array, count the delimiters first, create an array of that size plus one, and fill it in a second pass.
5) Why is strtok() not recommended in C++?
It changes the string we give it, it cannot be used on a const string or a string literal, it skips empty tokens, and it is not thread-safe because it remembers its position in a hidden static variable. For C++ string objects, the stringstream or find() methods are safer.
6) Can getline() split on more than one character?
No. The delimiter of getline() is a single char. To split on a longer delimiter like "::" or ", ", use find() with substr() and move ahead by the length of the delimiter. To split on several different characters, use find_first_of() or regex.