删除固定字符串和多余空格

  1. 替换成空格
  2. 去除超过一个的空格
  3. 去除前后的空格
  • 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;
}
···
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值