This task, commonly known as string trimming, can be accomplished using C 's string class. To address potential extra spaces between words, a separate operation called string reduction is employed.
To remove leading and trailing spaces, the trim() function can be defined using the find_first_not_of and find_last_not_of methods:
std::string trim(const std::string& str, const std::string& whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); }
To remove extra spaces between words, the reduce() function performs the following operations:
std::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " \t") { // trim first auto result = trim(str, whitespace); // replace sub ranges auto beginSpace = result.find_first_of(whitespace); while (beginSpace != std::string::npos) { const auto endSpace = result.find_first_not_of(whitespace, beginSpace); const auto range = endSpace - beginSpace; result.replace(beginSpace, range, fill); const auto newStart = beginSpace + fill.length(); beginSpace = result.find_first_of(whitespace, newStart); } return result; }
The following code demonstrates the usage of the trim() and reduce() functions:
int main(void) { const std::string foo = " too much\t \tspace\t\t\t "; const std::string bar = "one\ntwo"; std::cout << "[" << trim(foo) << "]" << std::endl; std::cout << "[" << reduce(foo) << "]" << std::endl; std::cout << "[" << reduce(foo, "-") << "]" << std::endl; std::cout << "[" << trim(bar) << "]" << std::endl; }
[too much space] [too much space] [too-much-space] [one two]
The above is the detailed content of How do I remove leading and trailing spaces, and reduce multiple spaces to single spaces in a C string?. For more information, please follow other related articles on the PHP Chinese website!