c string去除空格
时间: 2024-09-19 12:03:15 浏览: 47
在C++中,如果你想要从`std::string`对象中移除所有的空格,可以使用`erase()`和`find()`方法结合来实现。首先,你可以找到第一个非空格字符的位置,然后清除开头到这个位置的所有空格。接着,继续查找最后一个非空格字符并删除其后面的空格。下面是一个简单的示例:
```cpp
#include <iostream>
#include <string>
std::string removeSpaces(const std::string &str) {
if (str.empty()) return str; // 如果字符串为空直接返回
size_t start = 0;
for (size_t i = 0; i < str.length(); ++i) {
if (str[i] != ' ') { // 遇到非空格字符
str.erase(0, start); // 移除前导空格
str.insert(i, 1, str[start]); // 将非空格字符放回原位
start = i + 1; // 更新起始位置
}
}
if (start < str.length()) str.erase(start, str.length()); // 删除末尾多余的空格
return str;
}
int main() {
std::string input = "Hello World! This is a test.";
std::cout << "Original: " << input << std::endl;
std::string result = removeSpaces(input);
std::cout << "Without spaces: " << result << std::endl;
return 0;
}
```
当你运行这个程序,你会看到原始字符串"Hello World! This is a test."变为"HelloWorld!Thisisatest."。
阅读全文
相关推荐


















