c++删除<string>char数组中的空格
时间: 2025-01-19 08:04:53 浏览: 38
在C++中,可以通过多种方法删除`std::string`中的空格。以下是几种常见的方法:
### 方法一:使用`erase`和`remove`函数
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "This is a sample string with spaces.";
// 使用remove和erase函数删除空格
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
std::cout << str << std::endl; // 输出: Thisisasamplestringwithspaces.
return 0;
}
```
### 方法二:使用`std::copy_if`函数
```cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string str = "This is a sample string with spaces.";
std::string result;
// 使用std::copy_if函数删除空格
std::copy_if(str.begin(), str.end(), std::back_inserter(result), [](char c) {
return c != ' ';
});
std::cout << result << std::endl; // 输出: Thisisasamplestringwithspaces.
return 0;
}
```
### 方法三:使用循环和`std::string::find`函数
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "This is a sample string with spaces.";
std::string result;
for (size_t i = 0; i < str.length(); ++i) {
if (str[i] != ' ') {
result += str[i];
}
}
std::cout << result << std::endl; // 输出: Thisisasamplestringwithspaces.
return 0;
}
```
### 方法四:使用`std::regex`库
```cpp
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str = "This is a sample string with spaces.";
// 使用正则表达式删除空格
str = std::regex_replace(str, std::regex("\\s+"), "");
std::cout << str << std::endl; // 输出: Thisisasamplestringwithspaces.
return 0;
}
```
这些方法都可以有效地删除`std::string`中的空格。选择哪种方法取决于具体的需求和偏好。
阅读全文
相关推荐



















