Home > Backend Development > C++ > How Can I Efficiently and Elegantly Iterate Over Words in a String?

How Can I Efficiently and Elegantly Iterate Over Words in a String?

Linda Hamilton
Release: 2024-12-24 22:31:16
Original
1027 people have browsed it

How Can I Efficiently and Elegantly Iterate Over Words in a String?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template