首页 > 后端开发 > C++ > 如何在 C 中修剪字符串的前导和尾随空格?

如何在 C 中修剪字符串的前导和尾随空格?

Mary-Kate Olsen
发布: 2024-11-19 09:28:03
原创
421 人浏览过

How to Trim Leading and Trailing Spaces from a String in C  ?

从字符串中删除前导和尾随空格

在 C 中从字符串对象中修剪前导和尾随空格是一项常见任务。 string 类缺乏本地方法来实现此目的,但可以通过字符串操作技术的组合来实现。

要删除前导空格和尾随空格,可以使用 find_first_not_of 和 find_last_not_of 函数来识别第一个和最后一个字符串中的非空白字符。一旦确定了这些位置,就可以使用 substr 函数来提取没有前导空格和尾随空格的子字符串。

1

2

3

4

5

6

7

8

9

10

11

#include <string>

 

std::string trim(const std::string& str) {

    const auto strBegin = str.find_first_not_of(" ");

    if (strBegin == std::string::npos) {

        return "";

    }

    const auto strEnd = str.find_last_not_of(" ");

    const auto strRange = strEnd - strBegin + 1;

    return str.substr(strBegin, strRange);

}

登录后复制

扩展格式以减少额外空格

要删除字符串中单词之间的多余空格,需要更全面的方法。这可以通过重复使用 find_first_of、find_last_not_of 和 substr 函数将空格子范围替换为占位符字符或字符串来实现。

1

2

3

4

5

6

7

8

9

10

11

12

std::string reduce(const std::string& str, const std::string& fill = " ") {

    auto result = trim(str);

    auto beginSpace = result.find_first_of(" ");

    while (beginSpace != std::string::npos) {

        const auto endSpace = result.find_first_not_of(" ", beginSpace);

        const auto range = endSpace - beginSpace;

        result.replace(beginSpace, range, fill);

        const auto newStart = beginSpace + fill.length();

        beginSpace = result.find_first_of(" ", newStart);

    }

    return result;

}

登录后复制

使用示例

以下代码片段演示了如何使用这些函数:

1

2

3

4

5

6

7

8

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;

登录后复制

This代码将产生以下输出:

1

2

3

4

5

[too much               space] 

[too much space] 

[too-much-space] 

[one 

two]

登录后复制

以上是如何在 C 中修剪字符串的前导和尾随空格?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板