Home > Backend Development > C++ > How to Efficiently Parse a Comma-Separated String of Integers into an Array?

How to Efficiently Parse a Comma-Separated String of Integers into an Array?

Mary-Kate Olsen
Release: 2024-12-22 07:12:10
Original
328 people have browsed it

How to Efficiently Parse a Comma-Separated String of Integers into an Array?

Parsing a Comma-Separated String of Integers

The task in this question involves parsing a string containing comma-separated integers into an integer array. To accomplish this, a straightforward approach is recommended:

Input Processing:

  1. Create a string stream from the input string.
  2. Iterate over the string stream character by character.
  3. Read each number until encountering a comma (',').

Comma Handling:

  1. After extracting a number, check the next character in the string stream.
  2. If it's a comma, discard it to advance to the next number.
  3. If not, the iteration continues to extract the next number.

Populating the Array:

  1. With each extracted number, append it to an integer vector (to allow for dynamic resizing as needed).

Example Implementation:

Below is a C code example 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;
}
Copy after login

Benefits:

  • This approach is simple to understand and implement.
  • It's efficient for parsing large strings with numerous comma-separated numbers.
  • It's customizable for additional handling of special characters or other scenarios as needed.

The above is the detailed content of How to Efficiently Parse a Comma-Separated String of Integers into an Array?. 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