1、只清除字符串首尾的空格
方法一:调用string的成员函数来进行操作
#include<iostream>
#include<string>
#include<sstream>
using namespace std;int main()
{//str字符串首尾各有两个空格。string str = " hello this is just a test. ";int len1 = str.length();auto s1 = str.find_first_not_of(' ');string res = str.substr(s1);auto s2 = res.find_last_not_of(' ');// erase默认会从所给位置开始一直删除到字符串的末尾res.erase(s2+1);int len2 = res.length();cout << "len1= " << len1 << " \nlen2= " << len2 << " \nres= " << res << endl;system("pause");return 0;
}
方法二
#include<iostream>
#include<string>
#include<sstream>
using namespace std;int main()
{//str字符串首尾各有两个空格。string str = " hello this is just a test. ";int len1 = str.length();int i = 0;for (; i < len1; ++i){if (str[i] != ' ')break;}str.erase(0, i);i = str.length() - 1;for (; i >= 0; --i){if (str[i] != ' ')break;}str.erase(i + 1);int len2 = str.length();cout << "len1= " << len1 << " \nlen2= " << len2 << " \nstr= " << str << endl;system("pause");return 0;
}
2、清除字符串中所有的空格
方法一
#include<iostream>
#include<string>
#include<vector>
using namespace std;int main()
{//str字符串首尾各有两个空格。string str = " hello this is just a test. ";string tmp;vector<string> res;bool flag = false;for (int i = 0; i < str.length(); ++i){if (str[i] != ' '){tmp += str[i];flag = true;}else{if (flag){res.push_back(tmp);tmp.clear();flag = false;}}}for (auto &s : res)cout << s << endl;system("pause");return 0;
}
方法二:使用sstream
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;int main()
{//str字符串首尾各有两个空格。string str = " hello this is just a test. ";string tmp;vector<string> res;istringstream iss(str);while (iss >> tmp){res.push_back(tmp);}for (auto &s : res)cout << s << endl;system("pause");return 0;
}