C++ 一行代码删除string字符串中的“\n“、“\r“、“\t“ 和 所有空白字符

这篇博客记录如何删除C++字符串中的回车、换行、制表符和所有的空白字符!

方式一

示例:

std::string str = "\n\r\t   abc   \n\t\r   cba   \r\t\n";
std::cout << str << std::endl;

运行截图:

使用remove_if进行移除:

#include <cctype>
#include <algorithm>


std::string str = "\n\r\t   abc   \n\t\r   cba   \r\t\n";
str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
std::cout << str << std::endl;

::isspace 标识空白字符 

运行截图:

效果明显看得出来! 


方式二

#include <iostream>
#include <string>
#include <algorithm>
#include <locale>
#include <functional>

std::string s = "   \n\r\t   Hello \r\t\n\n   World   \n\r\t    ";
s.erase(std::remove_if(s.begin(),
		s.end(),
		std::bind(std::isspace<char>, std::placeholders::_1, std::locale::classic())),
		s.end());

std::cout << s << std::endl;

运行截图: 

 效果明显看得出来! 


方式三

#include <iostream>
#include <string>
#include <algorithm>


std::string s = "   \n\r\t   How \r\t\n\n   much   \n\r\t    ";
s.erase(std::remove_if(s.begin(), s.end(),
		[](char &c) {
			return std::isspace<char>(c, std::locale::classic());
		}),
		s.end());

std::cout << s << std::endl;

运行截图: 

  效果明显看得出来! 

猜你喜欢

转载自blog.csdn.net/cpp_learner/article/details/130266623
今日推荐