从 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