Removing Leading and Trailing Spaces from a String in C
Problem:
How do we efficiently remove leading and trailing spaces from a C string? Additionally, how can we extend this operation to remove extra spaces between words in the string?
Solution:
Removing Leading and Trailing Spaces:
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); }
Reducing Extra Spaces:
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; }
Example:
const std::string foo = " too much\t \tspace\t\t\t "; const std::string trimmedFoo = trim(foo); const std::string reducedFoo = reduce(foo); std::cout << "Original: " << foo << std::endl; std::cout << "Trimmed: " << trimmedFoo << std::endl; std::cout << "Reduced: " << reducedFoo << std::endl;
Output:
Original: too much space Trimmed: too much space Reduced: too-much-space
The above is the detailed content of How to Efficiently Remove Leading, Trailing, and Extra Spaces from a C String?. For more information, please follow other related articles on the PHP Chinese website!