Home > Backend Development > C++ > How Can I Efficiently Separate Comma-Delimited Strings in C ?

How Can I Efficiently Separate Comma-Delimited Strings in C ?

Patricia Arquette
Release: 2024-11-27 17:36:14
Original
304 people have browsed it

How Can I Efficiently Separate Comma-Delimited Strings in C  ?

Separating Comma-Delimited Strings Using Stringstream

In the provided problem, the task is to separate a comma-delimited string into individual tokens. While the stringstream::operator can effortlessly separate words by spaces, it falls short when it comes to commas.

To overcome this challenge, we employ a modified approach:

#include <iostream>
#include <sstream>

int main() {
  std::string input = "abc,def,ghi";
  std::istringstream ss(input);
  std::string token;

  // Use getline to separate by commas
  while (std::getline(ss, token, ',')) {
    std::cout << token << '\n';
  }

  return 0;
}
Copy after login

In this modified code:

  • We use std::getline instead of std::stringstream::operator>>. getline can extract substrings up to a specified delimiter (in this case, a comma).
  • We iterate over the input stream until no more tokens are found.
  • For each token, we print it on a new line.
  • The output accurately separates the input string into individual tokens:

    abc
    def
    ghi
    Copy after login

    The above is the detailed content of How Can I Efficiently Separate Comma-Delimited Strings in C ?. 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