Home >Backend Development >C++ >How Can I Easily Extract Numbers from a Comma-Delimited String in C ?
Easy Extraction of Numbers from Comma-Delimited Strings in C
Parsing a string containing a comma-separated list of numbers into an integer array is a straightforward task in C . To accomplish this, consider the following technique:
Iterate through the string character by character:
Code Implementation:
#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
This code successfully parses the comma-delimited string into an integer array, storing the individual numbers in the vector vect. The std::stringstream makes it easy to extract the numbers and check for the presence of commas.
The above is the detailed content of How Can I Easily Extract Numbers from a Comma-Delimited String in C ?. For more information, please follow other related articles on the PHP Chinese website!