Given a string:
std::string str{"This i_s A stRIng"};
Is it possible to transform it to lowercase and remove all non-alpha characters in a single pass?
Expected result:
this is a string
I know you can use std::transform(..., ::tolower) and string.erase(remove_if()) combination to make two passes, or it can be done manually by iterating each character, but is there a way to do something that would combine the std::transform and erase calls without having to run through the string multiple times?
That is exactly would you would have to do, eg:
Or:
You can use the standard
std::accumulate()algorithm, as shown in francesco's answer. Although, that will not manipulate thestd::stringin-place, as the code above does. It will create a newstd::stringinstead (and will do so on each iteration, for that matter).Otherwise, you could use C++20 ranges, ie by combining
std::views::filter()withstd::views::transform(), eg (I'm not familiar with the<ranges>library, so this syntax might need tweaking):But, this would actually be a multi-pass solution, just coded into a single operation.