Home > Backend Development > C++ > How Can I Efficiently Extract Integers from a Comma-Separated String in C ?

How Can I Efficiently Extract Integers from a Comma-Separated String in C ?

Mary-Kate Olsen
Release: 2024-12-29 10:02:09
Original
707 people have browsed it

How Can I Efficiently Extract Integers from a Comma-Separated String in C  ?

Extracting Numeric Data from Comma-Delimited Strings in C

Parsing data from comma-separated strings into numerical arrays presents a common challenge in programming. For the specific case of integer numbers, C provides several straightforward approaches.

Basic Parsing Algorithm:

One simple method involves iterating through the string character by character. For each character, check if the next character is a comma. If it is, discard the comma. Otherwise, convert the character to an integer and store it in the array.

Using istringstream:

The C Standard Library offers the istringstream class for parsing input streams. To extract numbers from a comma-delimited string, create an istringstream object with the string as input. Then, use the stream extraction operator >> to extract each number one at a time.

Implementation:

The following code snippet demonstrates the basic parsing algorithm using istringstream:

#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;

    return 0;
}
Copy after login

Other Options:

For more complex parsing scenarios, the C Standard Library provides additional options, such as the strtok function and regular expressions. However, for simple comma-delimited integer lists, the above methods are typically sufficient and straightforward to implement.

The above is the detailed content of How Can I Efficiently Extract Integers from a Comma-Separated String 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