How To Split a String in C++? 5 Methods Explained with Codes

How To Split a String in C++?

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. “Spilt Strings In C++” is one such advanced string concept that we have to learn.

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. 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 5 different methods that we can use.
  • While splitting the strings in C++, we have to keep in mind some of Memory Implications.

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. If you want to handle errors efficiently while working with strings, understanding Exception Handling in C++ is crucial.

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.

What are the Methods to Split Strings in C++? Read Below

Although C++ does not have a built-in ‘split()’ function like Java, it offers a plethora of alternatives to achieve the same outcome. If you’re interested in learning how Java handles string manipulations, check out our article on Comparing Strings in Java.

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 <bits/stdc++.h>
using namespace std;

int main() 
{
    string zap = "Sounetra 25 Writer";
    stringstream sg(zap); // Using Stringstream With String
    string a, b;
    int c;
    
    sg >> a >> c >> b; // Spiliting All The Strings
    cout << "Split Strings With Stringstream: " << endl;
    cout << a << "\n" << c << "\n" << b;
    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 uses space as the default 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: 

Using Only Stringstream

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 or a newline character (‘\n’). It then stores the extracted characters into the string specified by the user (‘str’).

				
					#include <bits/stdc++.h>
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 check each Delimiter and pick up the Word after 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: 

Output- Using Delimiter

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 <bits/stdc++.h>
using namespace std;


vector<string> split(string i, char d) // Method To Split String Using Find And Substr
{
    vector<string> ts; // Creating The Vector

    int s = 0; // Start Index Of First Token
    int 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 Stings 
        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: 

 Output- Using Find And Substr

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 delimiter character or string.
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 <bits/stdc++.h>
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
    char* t = strtok(const_cast<char*>(i.c_str()), 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 Stings 
        cout << t << endl;
    return 0;
}


				
			

Steps Of The Program: 

  • In this case, as well, the Spilt() 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: 

Output- Using Strtok

It’s important to note that strtok() converts C++ style strings to C-styled strings. It thus modifies the original string by inserting null terminators. Additionally, it is not
thread-safe, meaning it can have unexpected behavior in a multi-threaded environment.

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 <bits/stdc++.h>
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 Stings 
        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: 

Output- Using Custom Function

Understood this code? If you have any doubts or issues related to other C++ concepts and are struggling with your homework, then you can use CodingZap’s best C++ assignment help services.

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 Performance, Memory Efficiency, 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

Complexity

Easy

Moderate

Moderate

Moderate

Hard

Original String Modification

No

No

No

Yes

Depends on Implementation

Multiple Delimiter Support

No

Yes

Yes

Yes

Yes

Performance

Moderate

Fast

Fast

Fast

Variable

Memory Efficiency

Moderate

High

High

High

Depends on Implementation

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.
  • For Text Manipulation, the use of the String Splitting Process is needed.
  • String Splitting can sometimes be used for Handling User Inputs and Commands.
  • 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 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 have to always use the method that provides the Delimiter Argument Facility.
  • 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.
  • If we are using any Custom Function, we should optimize it to reduce the Memory Consumption.

Conclusion:

In the end, we can say it is very important to know about the “Spilt 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: 

  • 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 for better String Splitting.
  • If we are using Find(), Substr(), and Strtok(), we have to create Tokens first.
  • Delimiter Type, Memory Efficiency, Compatibility, etc. are some points that we keep in mind while splitting the string.