此任務通常稱為字串修剪,可以使用 C 的 string 類別來完成。為了解決單字之間潛在的額外空格,採用了一種稱為字串縮減的單獨操作。
要刪除前導和尾隨空格,可以使用trim() 函數定義find_first_not_of 和find_last_not_of 方法:
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; }用法以下程式碼示範了trim()和reduce()函數的用法:
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; }輸出
以上是如何在 C 字串中刪除前導空格和尾隨空格,並將多個空格減少為單一空格?的詳細內容。更多資訊請關注PHP中文網其他相關文章!