Eliminating Whitespace from C Strings
In C , removing spaces from a string can be a common task. A naive approach would involve iterating over the characters and manually constructing a new string. However, there is a more efficient solution.
The Algorithm
The C STL provides a powerful algorithm called remove_if, which can be employed for this purpose. This algorithm takes a predicate function that determines whether an element should be removed, and then removes all such elements from the container.
In this case, the predicate function we are interested in is isspace, which returns true for whitespace characters and false otherwise. By applying remove_if to a string with the isspace predicate, we can eliminate all whitespace characters.
Implementation
Once the whitespace characters have been removed using remove_if, we need to shrink the string to its new size. This can be achieved using the erase method. Here is a complete implementation of this approach:
#include <algorithm> #include <string> void remove_spaces(std::string& str) { str.erase(std::remove_if(str.begin(), str.end(), std::isspace), str.end()); }
Custom Implementation of remove_if
The remove_if algorithm from the STL is a generic function that can be applied to containers beyond strings. However, for specific use cases like this one, it may be more convenient to implement a custom version that is tailored to strings:
template <typename T> T remove_if(T beg, T end, std::function<bool(char)> pred) { T dest = beg; for (T itr = beg; itr != end; ++itr) { if (!pred(*itr)) { *(dest++) = *itr; } } return dest; }
This custom implementation mimics the behavior of the STL remove_if algorithm and can be used specifically for character-based containers like std::string.
The above is the detailed content of How Can I Efficiently Remove Whitespace from C Strings?. For more information, please follow other related articles on the PHP Chinese website!