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:
Comma Handling:
Populating the Array:
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; }
Benefits:
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!