Gice

Technology and General Blog

Doing work with string details is an necessary element of any programming language. Occasionally we need to split the string information for programming uses. The split() purpose exists in several programming languages to divide the string into numerous parts. There is no crafted-in break up() function in C++ for splitting string but quite a few a number of methods exist in C++ to do the exact same job, such as applying getline() functionality, strtok() functionality, making use of find() and erase() features, and many others. The employs of these functions to split strings in C++ have been discussed in this tutorial.

Pre-requisite

Before examining the illustrations of this tutorial, you have to examine the g++ compiler is put in or not in the program. If you are employing Visible Studio Code, then install the necessary extensions to compile the C++ source code to develop the executable code. Right here, the Visible Studio Code software has been utilized to compile and execute the C++ code.

Split string applying getline() function

The getline() purpose is made use of to study characters from a string or a file material right up until a particular delimiter or separator is observed and store every single parse string into a further string variable. The operate will keep on the process right up until the total written content of the string or file is parsed. The syntax of this purpose is supplied below.

Syntax:

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

Listed here, the very first parameter, isstream, is the item from where by the people will be extracted. The next parameter is a string variable that will retailer the extracted worth. The 3rd parameter is utilized to established the delimiter that will use for extracting the string.

Produce a C++ file with the subsequent code to split a string based on the room delimiter using the getline() purpose.  A string value of a number of phrases has been assigned into a variable, and area has been utilised as the separator. A vector variable has been declared to store the extracted words and phrases. Following, the ‘for’ loop has utilized to print each and every benefit from the vector array.

//Contain vital libraries
#consist of
#contain
#consist of
#consist of

int major()

    //Define string information that will be splitted
    std::string strData = “Learn C++ Programming”
    //Define contant facts that will be labored as delimiter
    const char separator = ‘ ‘
    //Define the dynamic array variable of strings
    std::vector outputArray
    //Assemble a stream from the string
    std::stringstream streamData(strData)
    /*
    Declare string variable that will be applied
    to retail outlet data soon after break up
    */

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

    whilst (std::getline(streamData, val, separator))
        outputArray.press_back again(val)
   
    //Print the splitted facts
    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 :[email protected] :+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 : %sn, tokenValue)
        else if(counter == 2)
            printf(“Occupation : %sn, tokenValue)
        else if(counter == 3)
            printf(“Email : %sn, tokenValue)
        else
            printf(“Mobile No. : %sn, 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++.

Leave a Reply

Your email address will not be published. Required fields are marked *