How to split a string with delimiter in C++?

by dandre.keeling , in category: C/C++ , 2 years ago

How to split a string with delimiter in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dee_smith , 2 years ago

@dandre.keeling As an example, you can use the strtok function to split any string by delimiter in C++. Code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<cstring>

int main() {
    char str[] = "test string example";

    // Split a string by space
    char *ptr = strtok(str, " ");

    while (ptr != nullptr) {
        printf(" %s\n", ptr);
        ptr = strtok(nullptr, " ");
    }
    // Output:
    // test
    // string
    // example

    return 0;
}
by moriah.medhurst , 10 months ago

@dandre.keeling 

In C++, you can split a string with a delimiter using the stringstream class and the getline function. Here's an example code that splits a string by a comma delimiter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::string str = "apple,banana,orange";
  std::vector<std::string> tokens;
  std::stringstream ss(str);
  std::string token;

  while (getline(ss, token, ',')) {
    tokens.push_back(token);
  }

  for (auto& t : tokens) {
    std::cout << t << std::endl;
  }

  return 0;
}


In this code, we first define a string that contains our input string with comma-separated values. We also create a vector to store the individual tokens. Next, we create a stringstream object from the input string and iterate through it using a while-loop.


In each iteration, we use the getline function to extract a token delimited by a comma. The extracted token is then added to our tokens vector. Finally, we print out each token using a range-based for-loop.


This code can be easily modified to split a string with a different delimiter. Simply replace the comma delimiter with the desired character in the getline function call.