c++ std20 字符串 去掉空格
时间: 2024-09-07 18:02:26 浏览: 108
在C++20标准库中,你可以使用std::remove_if()
函数结合std::isspace()
来去掉字符串中的所有空格。std::isspace()
是一个字符分类函数,如果输入的是空白字符(包括空格、制表符、换行符等),它会返回true
。下面是一个简单的示例:
#include <string>
#include <algorithm>
#include <cctype>
std::string remove_spaces(const std::string& str) {
str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
return str;
}
int main() {
std::string original_str = "Hello World with spaces";
std::string result = remove_spaces(original_str);
std::cout << "Original string: " << original_str << "\n";
std::cout << "String without spaces: " << result << "\n";
return 0;
}
在这个例子中,std::remove_if()
找到所有的空格字符并从原始字符串中移除它们,最后返回处理后的字符串。
相关推荐












