C++标准库无trim函数,需手动实现。通过std::isspace配合循环查找首尾非空白字符,再用substr或erase提取或删除空白,可安全高效去除字符串首尾空格、制表符、换行等空白字符。

在C++中,标准库没有提供像其他语言那样的trim()函数来去除字符串首尾的空白字符,但可以通过std::string的成员函数结合std::isspace等工具手动实现。下面介绍一种常用且高效的方法,用于去除字符串首尾的空白字符(包括空格、制表符、换行等)。
可以编写两个辅助函数:一个用于查找第一个非空白字符的位置,另一个用于查找最后一个非空白字符的位置,然后使用substr提取中间部分。
#include <string>
#include <cctype>
#include <iostream>
<p>std::string trim(const std::string& str) {
if (str.empty()) return str;</p><pre class='brush:php;toolbar:false;'>size_t start = 0;
size_t end = str.length() - 1;
// 找到第一个非空白字符
while (start <= end && std::isspace(static_cast<unsigned char>(str[start]))) {
++start;
}
// 找到最后一个非空白字符
while (end >= start && std::isspace(static_cast<unsigned char>(str[end]))) {
--end;
}
return str.substr(start, end - start + 1);}
立即学习“C++免费学习笔记(深入)”;
说明:
std::isspace判断字符是否为空白(需包含<cctype></cctype>)。static_cast<unsigned char></unsigned>是为了避免char为负值时传递给std::isspace导致未定义行为。
int main() {
std::string s = " \t Hello World \n ";
std::cout << "[" << trim(s) << "]" << std::endl;
// 输出: [Hello World]
return 0;
}
如果只想去除空格(不包括制表符或换行),可将std::isspace替换为比较' ':
while (start <= end && str[start] == ' ') ++start; while (end >= start && str[end] == ' ') --end;
若希望直接修改原字符串,可使用erase:
void trim_inplace(std::string& str) {
if (str.empty()) return;
<pre class='brush:php;toolbar:false;'>size_t start = 0;
size_t end = str.length() - 1;
while (start <= end && std::isspace(static_cast<unsigned char>(str[start])))
++start;
str.erase(0, start);
end = str.length() - 1; // 更新end位置
while (end != std::string::npos && std::isspace(static_cast<unsigned char>(str[end])))
--end;
str.erase(end + 1);}
立即学习“C++免费学习笔记(深入)”;
基本上就这些。这个方法简洁、安全,适用于大多数C++项目中的字符串去空需求。
以上就是C++ string去除空格_C++ trim去除首尾空白字符的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号