- 替换成空格
- 去除超过一个的空格
- 去除前后的空格
- erase(pos, n);
删除从pos开始的n个字符,比如erase(0, 1)就是删除第一个字符
erase(1) 从下标1到末尾连续删除 - erase(position);
删除position处的一个字符(position是个string类型的迭代器) str.erase(str.begin()+2);
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
str = "WUBWUBWUBIWUBWUBAMWUBWUBWUBXWUBWUB";
int i = 0,j=2;
int n = str.size();
while (j < n) {
string temp = str.substr(i,3);
if (temp == "WUB") {
str = str.replace(i, 3," ");
n -= 2;
}
i++;
j++;
}
//双指针法
bool space = false;
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < n; fastIndex++) {
if (str[fastIndex] != ' ') {
str[slowIndex++]=str[fastIndex];
space=false;
}
else {
if (space != true) {
space = true;
str[slowIndex++] = str[fastIndex];
}
else continue ;
}
}
str = str.substr(0, slowIndex);
//if (str[0] == ' ') str.erase(0,1);
//if (str[str.size()-1]==' ') str.erase(str.size() - 1,1);
str.erase(0, str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return 0;
}
regex正则表达式
匹配字符类的重复
- 0次或多次。贪婪重复。
- 1次或多次。
? 0次或1次。
{m,n} 给定[m,n]次
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main(){
string str = "WUBWUBWUBIWUBWUBAMWUBWUBXWUBWUB";
regex e("(WUB)+"); //regex 表示一个正则表达式类
string result = regex_replace(str, e, " ");
result.erase(0, result.find_first_not_of(' '));
result.erase(result.find_last_not_of(' ') + 1);
return 0;
}
···