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; }
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!