2 Star 5 Fork 0

Monomania/LeetCode_Algorithm_Plus

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
去除空格.cpp 2.76 KB
一键复制 编辑 原始数据 按行查看 历史
#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;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/monamania/leetcode_algorithm_plus.git
git@gitee.com:monamania/leetcode_algorithm_plus.git
monamania
leetcode_algorithm_plus
LeetCode_Algorithm_Plus
master

搜索帮助

Cb406eda 1850385 E526c682 1850385