C++ 去除string 类型里的空格
时间: 2023-09-30 07:07:26 浏览: 273
可以使用C++标准库中的算法库和字符串库来去除string类型中的空格。具体方法如下:
1. 使用`std::remove_if`算法删除空格
```cpp
#include <algorithm>
#include <string>
std::string str = " Hello, world! ";
str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
// str现在的值为"Hello,world!"
```
这里使用了`std::isspace`函数来判断字符是否为空格,`::`是用来限定作用域的。
2. 使用循环删除空格
```cpp
#include <string>
std::string str = " Hello, world! ";
for (auto it = str.begin(); it != str.end(); ) {
if (::isspace(*it)) {
it = str.erase(it);
} else {
++it;
}
}
// str现在的值为"Hello,world!"
```
这个方法使用了一个循环来遍历字符串,如果遇到空格就删除它。
两种方法的效果是相同的,只是实现方式不同。
相关问题
c++中使用正则表达式去除string 类型中的空格
可以使用C++11中的正则表达式库`<regex>`来去除string类型中的空格,具体代码如下:
```c++
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string str = "hello world";
std::regex pattern("\\s+"); // 匹配一个或多个空格
std::string result = std::regex_replace(str, pattern, "");
std::cout << "原字符串:" << str << std::endl;
std::cout << "去除空格后的字符串:" << result << std::endl;
return 0;
}
```
运行结果:
```
原字符串:hello world
去除空格后的字符串:helloworld
```
C++ string类型的去除特殊符号函数
以下是一个简单的实现,可以去除 string 类型中的特殊符号:
```c++
#include <iostream>
#include <string>
std::string remove_special_chars(const std::string& str)
{
std::string result;
for (char c : str)
{
if (isalnum(c) || isspace(c))
{
result += c;
}
}
return result;
}
int main()
{
std::string input = "Hello, World! This is a string with special characters.";
std::string output = remove_special_chars(input);
std::cout << "Input: " << input << std::endl;
std::cout << "Output: " << output << std::endl;
return 0;
}
```
在上述代码中,`remove_special_chars` 函数接受一个 string 类型的参数 `str`,并返回一个去除特殊符号后的 string 类型结果。该函数遍历输入字符串中的每个字符,如果该字符是字母、数字或空格,则将其添加到输出字符串中。
请注意,上述代码仅仅是一个简单的实现,如果需要更复杂的字符串操作,可以使用正则表达式或其他库来实现。