Iterating Over Strings: Elegance Meets Efficiency
Iterating over the individual words of a string, especially when separated by whitespace, is a common programming task. While various approaches exist, finding an elegant and efficient solution can be challenging.
Current Method Using StringStream
The example provided utilizes a stringstream, but the OP seeks a more elegant solution. This method is certainly robust, but it involves some character manipulation and is not as concise as desired.
Elegant Solution: Splitting Strings
To achieve both elegance and efficiency, we can utilize C 's split() function. This function takes a string and a delimiter as input and returns a vector containing the split words.
#include <vector> #include <string> template <typename Out> void split(const std::string &s, char delim, Out result) { std::istringstream iss(s); std::string item; while (std::getline(iss, item, delim)) { *result++ = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; }
This solution requires minimal code and is easy to understand. It simply reads the string into a stringstream and uses the getline() function to extract individual words using the specified delimiter. The split strings can then be stored in a vector for further processing.
Do keep in mind, however, that this solution does not skip empty tokens. If you need to remove empty strings, you can further post-process the vector.
The above is the detailed content of How Can I Efficiently and Elegantly Iterate Over Words in a String?. For more information, please follow other related articles on the PHP Chinese website!