Home > Backend Development > C++ > body text

How to Split a C std::string Using Tokens (';')?

DDD
Release: 2024-11-22 19:29:13
Original
997 people have browsed it

How to Split a C   std::string Using Tokens (

Splitting C std::string Using Tokens (";")

Assuming you have a string composed of words separated by semicolons (";"), you aim to split this string into a vector of separate words.

To achieve this, you can leverage the standard library function std::getline. It allows you to read data from a string stream, treating it as a sequence of lines. By defining a delimiter, you can instruct std::getline to split the string into substrings based on that delimiter.

Here's a sample code demonstrating how to do this:

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

using namespace std;

int main() {
    vector<string> strings;
    istringstream f("denmark;sweden;india;us");
    string s;

    while (getline(f, s, ';')) {
        cout << s << endl;
        strings.push_back(s);
    }

    return 0;
}
Copy after login

In this code:

  • A vector strings is created to store the split substrings.
  • A string stream f is initialized with the input string containing the semicolon-separated words.
  • Within the while loop:

    • getline is invoked with the delimiter ';' to extract the next substring s from the string stream.
    • The extracted substring is printed and added to the strings vector.

This approach provides a simple and efficient way to split a string using a specified token, such as ";".

The above is the detailed content of How to Split a C std::string Using Tokens (';')?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template