此任务通常称为字符串修剪,可以使用 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); }
为了删除单词之间的多余空格,reduce() 函数执行以下操作:
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; }
[too much space] [too much space] [too-much-space] [one two]
以上是如何在 C 字符串中删除前导空格和尾随空格,并将多个空格减少为单个空格?的详细内容。更多信息请关注PHP中文网其他相关文章!