How to split a string by comma in C++?

Member

by charles , in category: C/C++ , 2 years ago

How to split a string by comma in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@charles you can use strtok() function to split a given string by comma delimiter in c++, code:


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

int main() {
    char str[] = "Test,as,an,example";
    char *delim = ",";

    char *token = strtok(str, delim);

    while (token != nullptr)
    {
        printf("%s\n", token);
        token = strtok(nullptr, delim);
    }
    // Output:
    // Test
    // as
    // an
    // example

    return 0;
}


Member

by hailie , a year ago

@charles 

You can split a string by comma in C++ using the stringstream class and getline function. Here's an example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include 
#include 
#include 
#include 

int main() {
    // initialize the string
    std::string str = "apple,banana,orange";

    // create a stringstream object
    std::stringstream ss(str);

    // initialize a vector to store the splitted strings
    std::vector splitted;

    // use getline function to split the string by comma
    std::string token;
    while (getline(ss, token, ',')) {
        splitted.push_back(token);
    }

    // print the splitted strings
    for (const auto& s : splitted) {
        std::cout << s << std::endl;
    }

    return 0;
}


Output:

1
2
3
apple
banana
orange