從C 語言中的字符串中刪除前導和尾隨空格
問題:
如何我們可以有效地從C 字串中刪除前導和尾隨空格嗎?另外,我們如何擴展此操作以刪除字串中單字之間的多餘空格?
解決方案:
刪除前導和尾隨空格:
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); }
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; }
輸出:
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;
輸出:
Original: too much space Trimmed: too much space Reduced: too-much-space
以上是如何有效地刪除 C 字串中的前導、尾隨和多餘空格?的詳細內容。更多資訊請關注PHP中文網其他相關文章!