Home > Article > Backend Development > How can I trim and reduce strings in C ?
Trimming and reducing strings are common operations in programming. Trimming refers to removing leading and trailing whitespace characters from a string, while reducing involves replacing consecutive whitespace characters with a single predefined character or string.
To trim a string in C , you can use the find_first_not_of and find_last_not_of methods to identify the first and last non-whitespace characters. The code below illustrates this approach:
#include <string> std::string trim(const std::string& str) { const auto strBegin = str.find_first_not_of(" \t"); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(" \t"); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); }
Reducing a string involves replacing consecutive whitespace characters with a predefined character or string. Here's a function that performs this operation:
std::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " \t") { // trim first auto result = trim(str); // 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; }
Here's an example demonstrating the usage of the trim and reduce functions:
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 can I trim and reduce strings in C ?. For more information, please follow other related articles on the PHP Chinese website!