從C 中的字串中刪除前導和尾隨空格
C 中的字串操作通常涉及從字串中刪除不必要的空格。這對於資料清理或文字處理等任務特別有用。
刪除前導和尾隨空格
要刪除前導和尾隨空格,可以使用 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); }
刪除單字之間的多餘空格
要刪除單字之間的多餘空格,需要執行額外的步驟。這可以透過使用find_first_of、find_last_of、find_first_not_of 和find_last_not_of 方法以及substr 將多餘的空格替換為單一空格來實現:
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 bar = "one\ntwo"; std::cout輸出:
[too much space] [too much space] [too-much-space] [one two]
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3