How do I parse a string into an array in C++?
For example: "[1:2:3:4]cd/dvd PLDS DVD-RW DU8A6SH DU53 /dev/sr0"
I want to get an array of integers inside the square bracket []
. So the array contains {1, 2, 3, 4}
.
Below is the code I wrote, but I am not sure if this is the most efficient way to approach it.
std::string test = "[1:2:3:4]cd/dvd PLDS DVD-RW DU8A6SH DU53 /dev/sr0";
int begin = test.find("[");
begin = begin + 1;
std::string sub = test.substr(begin,7);
std::replace(sub.begin(), sub.end(), ':', ' ');
std::vector<int> arr;
std::stringstream ss(sub);
int temp;
while (ss >> temp)
arr.push_back(temp);
Note: Something will not be before "["
. "["
will always be present. The numbers will always be one digit each. There will always be four integers inside the square brackets. "]"
will always be present. Text always follows after the "]"
.
Aucun commentaire:
Enregistrer un commentaire