This blog records how to delete carriage returns, newlines, tabs and all blank characters in C++ strings!
method one
Example:
std::string str = "\n\r\t abc \n\t\r cba \r\t\n";
std::cout << str << std::endl;
Run the screenshot:
Use remove_if to remove:
#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 identifies whitespace characters
Run the screenshot:
The effect is clearly visible!
way two
#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;
Run the screenshot:
The effect is clearly visible!
way three
#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;
Run the screenshot:
The effect is clearly visible!