c++string.trim()
时间: 2023-07-21 18:06:04 浏览: 189
C++标准库中并没有直接提供字符串的trim()函数。不过,你可以使用一些其他方法来实现字符串的trim操作。一个常用的方法是使用C++的标准库算法和字符串处理函数,如下所示:
```cpp
#include <algorithm>
#include <cctype>
#include <string>
// 去除字符串首尾的空白字符
std::string trim(const std::string& str) {
// 找到第一个非空白字符的位置
auto start = std::find_if(str.begin(), str.end(), [](unsigned char ch) {
return !std::isspace(ch);
});
// 找到最后一个非空白字符的位置
auto end = std::find_if(str.rbegin(), str.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base();
// 返回修剪后的字符串
return (start < end ? std::string(start, end) : std::string());
}
```
使用上述函数,你可以去除字符串首尾的空白字符,包括空格、制表符、换行符等。例如:
```cpp
std::string str = " Hello, World! ";
std::string trimmed = trim(str);
```
在上述示例中,`trimmed` 将会是 `"Hello, World!"`。注意,这个函数只会去除字符串首尾的空白字符,不会修改中间的空白字符。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)