Split String by comma in C++

Split String by comma in C++

In this article, we will split a string by comma in C++.

There are several methods available to achieve this. For this, we can create a function and use some inbuilt functions.

Using the for loop

In this method, we will loop through a string using the for loop and check each character individually, whether it is a comma or not. For this, we will create a user-defined function.

For example,

Output:

7
8
9
5

In the above example,

  • The split_c() function will split the string by commas.
  • We traverse through each element of the string using the for loop.
  • We check if a character is a comma and if not, then we print it.

Using the getline() function

The getline() function can extract some required substring from a given string and store it till it encounters a given delimiter character. This function can split a string by commas.

For example,

Output:

7
8
9
5

In the above example,

  • The good() function will run the loop till the superstring object is valid and has not reached its end.
  • The getline() function will read characters and store them in the subtring string until the function encounters a comma.
  • We add this substring to the final vector using the push_back() function.

Using the strtok() function

The strtok() function splits a string and returns tokens (chunks of string) separated by a delimiter character.

To split a string by commas, we specify the delimiter as a comma. This is the most direct method available.

For example,

Output:

7
8
9
5

In the above example,

  • A pointer stores the tokens that we split using the strtok() function.
  • We call the function again while displaying to move on to the next token.
  • If we do not do this, the code will print the first element infinite times.
  • This function does not work with string variables and requires the string to be a char*.

Using the std::string::erase() and std::string::find() function

We can use the erase() function and find() function to split a string by commas in C++. To achieve this, we first set the delimiter as a comma and find the occurrences of this character in the string using the find() function.

Then, we proceed to erase the substring till the length of the delimiter, which in our case is 1. This will remove the commas, essentially splitting the string.

We implement this in the following code.

Output:

7
8
9
5

That’s all about how to split String by comma in C++.

Was this post helpful?

Leave a Reply

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