How to split string in C++

Working with string data is an essential part of any programming language. Sometimes we need to split the string data for programming purposes. The split() function exists in many programming languages to divide the string into multiple parts. There is no built-in split() function in C++ for splitting string but many multiple ways exist in C++ to do the same task, such as using getline() function, strtok() function, using find() and erase() functions, etc. The uses of these functions to split strings in C++ have been explained in this tutorial.

Pre-requisite

Before checking the examples of this tutorial, you have to check the g++ compiler is installed or not in the system. If you are using Visual Studio Code, then install the necessary extensions to compile the C++ source code to create the executable code. Here, the Visual Studio Code application has been used to compile and execute the C++ code.

Split string using getline() function

The getline() function is used to read characters from a string or a file content until a particular delimiter or separator is found and store each parse string into another string variable. The function will continue the task until the full content of the string or file is parsed. The syntax of this function is given below.

Syntax:

istream& getline(istream& is, string& str, char delim);

Here, the first parameter, isstream, is the object from where the characters will be extracted. The second parameter is a string variable that will store the extracted value. The third parameter is used to set the delimiter that will use for extracting the string.

Create a C++ file with the following code to split a string based on the space delimiter using the getline() function.  A string value of multiple words has been assigned into a variable, and space has been used as the separator. A vector variable has been declared to store the extracted words. Next, the ‘for’ loop has used to print each value from the vector array.

//Include necessary libraries
#include
#include
#include
#include

int main()
{
    //Define string data that will be splitted
    std::string strData = "Learn C++ Programming";
    //Define contant data that will be worked as delimiter
    const char separator = ' ';
    //Define the dynamic array variable of strings
    std::vector outputArray;
    //Construct a stream from the string
    std::stringstream streamData(strData);
    /*
    Declare string variable that will be used
    to store data after split
    */

    std::string val;
    /*
    The loop will iterate the splitted data and
    insert the data into the array
    */

    while (std::getline(streamData, val, separator)) {
        outputArray.push_back(val);
    }
    //Print the splitted data
    std::cout << "The original string is:" << strData << std::endl;
    //Read the array and print the splitted data
    std::cout << "\nThe values after splitting the string based on space:" << std::endl;
    for (auto &val: outputArray) {
        std::cout << val << std::endl;
    }
    return 0;
}

Output:

The following output will appear after executing the above code.

Split string using strtok() function

The strtok() function can be used to split a string by tokenizing the part of the string based on a delimiter. It returns a pointer to the next token if it exists; otherwise, it returns a NULL value. The string.h header file is required to use this function. A loop will require reading all splitted values from the string. The first argument contains the string value that will be parsed, and the second argument contains the delimiter that will be used to generate the token. The syntax of this function is given below.

Syntax:

char * strtok ( char * str, const char * delimiters );

Create a C++ file with the following code to split a string by using the strtok() function.   An array of characters is defined in the code containing a colon(‘:’) as the separator. Next, the strtok() function is called with the string value and the delimiter to generate the first token. The ‘while’ loop is defined to generate the other tokens and the token values until the NULL value is found.

//Include necessary libraries
#include
#include
int main()
{
    //Declare an array of characters
    char strArray[] = "Mehrab Hossain :IT Professional :mahrab@gmail.com :+8801726783423";
    //Return the first token value based on ':'
    char *tokenValue = strtok(strArray, ":");
    //Initialize the counter variable
    int counter = 1;
    /*
    Iterate the loop to print the token value
    and split the remaining string data to get
    the next token value
    */

    while (tokenValue != NULL)
    {
        if(counter == 1)
            printf("Name : %s\n", tokenValue);
        else if(counter == 2)
            printf("Occupation : %s\n", tokenValue);
        else if(counter == 3)
            printf("Email : %s\n", tokenValue);
        else
            printf("Mobile No. : %s\n", tokenValue);
            tokenValue = strtok(NULL, ":");
            counter++;
    }
    return 0;
}

Output:

The following output will appear after executing the above code.

Split string using find() and erase() functions

The string can be splitted in C++ by using find() and erase() functions. Create a C++ file with the following code to check the uses of find() and erase() functions to split a string value based on a particular delimiter. The token value is generated by finding the delimiter position by using the find() function, and the token value will be stored after removing the delimiter by using erase() function. This task will be repeated until the full content of the string is parsed. Next, the values of the vector array will be printed.

//Include necessary libraries
#include
#include
#include

int main(){
//Define the string
std::string stringData = "Bangladesh and Japan and Germany and Brazil";
//Define the separator
std::string separator = "and";
//Declare the vector variable
std::vector country{};
//Declare integer variable
int position;
//Declare string variable
std::string outstr, token;

/*
Split the string using substr() function
and adding the splitted word into the vector
*/

while ((position = stringData.find(separator)) != std::string::npos) {
token = stringData.substr(0, position);
//Remove the extra space from the front of the splitted string
country.push_back(token.erase(0, token.find_first_not_of(" ")));
stringData.erase(0, position + separator.length());
}
//Print all splitted word except the last one
for (const auto &outstr : country) {
std::cout << outstr << std::endl;
}
//Print the last splitted word
std::cout << stringData.erase(0, stringData.find_first_not_of(" ")) << std::endl;
return 0;
}

Output:

The following output will appear after executing the above code.

Conclusion

Three different ways to split a string in C++ have been explained in this tutorial by using simple examples to help the new python users to perform the split operation easily in C++.



from Linux Hint https://ift.tt/3y40nhM

Post a Comment

0 Comments