从 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中文网其他相关文章!