Home > Backend Development > C++ > body text

How to Split a String into Tokens in C Using std::getline()?

Barbara Streisand
Release: 2024-11-20 16:38:11
Original
671 people have browsed it

How to Split a String into Tokens in C   Using std::getline()?

Separating String Tokens Using C std::string

This question addresses the challenge of splitting a C std::string into multiple tokens, particularly using the delimiter ";". While some suggested solutions involve external libraries like Boost, the guidelines for this project prohibit their use. Therefore, we explore a more straightforward approach using the C Standard Library.

One effective method is to utilize the std::getline() function, which offers versatility in specifying delimiters. In this case, we can implement the tokenization process as follows:

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings; // Vector to store split strings
    istringstream f("denmark;sweden;india;us"); // Input stringstream
    string s; // Variable to store individual strings

    while (getline(f, s, ';')) {
        cout << s << endl; // Display split string
        strings.push_back(s); // Store string in vector
    }
}
Copy after login

In this implementation, we create a stringstream from the input string "denmark;sweden;india;us". The std::getline() function is employed to iterate over the stringstream and retrieve tokens separated by the ";" delimiter. Each retrieved token is both printed and added to the strings vector for further processing.

By employing this approach, we achieve the desired tokenization of the input string without relying on external libraries, adhering to the specified guidelines.

The above is the detailed content of How to Split a String into Tokens in C Using std::getline()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template