Home >Backend Development >C++ >How to Parse a Comma-Separated String into an Integer Array in C ?

How to Parse a Comma-Separated String into an Integer Array in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 03:14:14362browse

How to Parse a Comma-Separated String into an Integer Array in C  ?

Parsing Comma-separated Strings into Integer Arrays

In C , parsing a comma-separated string into an integer array can be achieved using the following steps:

  1. Read one number at a time: Use an input stream (std::istringstream) to read numbers from the string character by character.
  2. Check for commas: After reading a number, check if the next character is a comma (','). If so, ignore it.
  3. Push numbers into an array: Iterate over the input stream until all numbers are extracted. Store each number in a dynamically growing array (e.g., std::vector).

Here's an example code snippet that demonstrates this approach:

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

int main()
{
    std::string str = "1,2,3,4,5,6";
    std::vector<int> vect;

    std::stringstream ss(str);

    for (int i; ss >> i;) {
        vect.push_back(i);    
        if (ss.peek() == ',')
            ss.ignore();
    }

    for (std::size_t i = 0; i < vect.size(); i++)
        std::cout << vect[i] << std::endl;
}

Output:

1
2
3
4
5
6

The above is the detailed content of How to Parse a Comma-Separated String into an Integer Array in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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