代码拉取完成,页面将自动刷新
#include<iostream>
#include <string>
// #define NDEBUG
#include <assert.h>
#include <boost/algorithm/string.hpp>
#include <functional>
#include <iterator>
#include <algorithm> // std::minmax_element
using namespace boost;
using namespace std;
bool isSpace(char x) { return x == ' '; }
//函数原型
// template<class ForwardIt, class UnaryPredicate>
// ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
// {
// first = std::find_if(first, last, p);
// if (first != last)
// for(ForwardIt i = first; ++i != last; )
// if (!p(*i))
// *first++ = std::move(*i);
// return first;
// }
// template<typename T, typename P>
// T remove_if(T beg, T end, P pred)
// {
// T dest = beg;
// for (T itr = beg;itr != end; ++itr)
// if (!pred(*itr))
// *(dest++) = *itr;
// return dest;
// }
int main(int argc, const char** argv) {
/* 去除首尾空格 */
string str1 = " hello world! ";
boost::trim(str1); // str1 == "hello world!"
cout << str1 << endl;
/* 去除首尾空格2 */
int i = 0;
while(str1[i]==' ') i++;
int j = str1.size()-1;
while(str1[j]==' ') j--;
str1 = str1.substr(i, j - i + 1);
/* 去除所有空格 法一*/
string str2 = " hello world! ";
boost::erase_all(str2, " ");
cout << str2 << endl;
/* 去除所有空格 法二*/
string str3 = " hello world! ";
// str3.erase(std::remove_if(str3.begin(), str3.end(), std::isspace), str3.end());
str3.erase(std::remove_if(str3.begin(), str3.end(), isSpace), str3.end());
cout << str3 << endl;
/* 去除前空格 法一*/
string str4 = " sshah hha a";
str4.erase(str4.begin(), std::find_if(str4.begin(), str4.end(),
std::not1(std::ptr_fun(::isspace))));
cout << str4 << endl;
/* 去除前空格 法二*/
string str5 = " sshah hha ";
str5.erase(0, str5.find_first_not_of(" "));
std::cout << str5 << std::endl;
/* 去除后空格 法一*/
string str6 = " sshah hha ";
str6.erase(std::find_if(str6.rbegin(), str6.rend(),
std::not1(std::ptr_fun(::isspace))).base(),str6.end());
cout << str6 << endl;
/* 去除后空格 法二*/
string str7 = " sshah hha ";
str7.erase(str7.find_last_not_of(" ") + 1);
std::cout << str7 << std::endl;
/* 去除所有空格 法一*/
string word = " sshah hha ";
std::string::iterator end_pos = std::remove(word.begin(), word.end(), ' ');
word.erase(end_pos, word.end());//移除空格
cout << word << endl;
/* 去除所有空格 法二*/
string word2 = " sshah hha ";
remove_if(word2.begin(), word2.end(), isSpace);
cout << word2 << endl;
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。