STLのstring

子串查找替换

示例:

#include <iostream>
//#include <string>
using namespace std;

int main() {
	string s = "abchelloabcworldabccode!";
	string k = "abc";
	string t = " ";
	int i = 0;
	
	while(true) {
        //find的第一个参数k代表子串,第二个参数i表示从位置i开始查找
		i = s.find(k, i);
		if(i == -1)		break;
        //replace的第一个参数i表示从位置i开始替换,第二个参数表示目标替换字串的长度,第三个参数k表示目标替换字串
		s.replace(i, k.size(), t);
	}
	cout<<s;
	return 0;
}

代码说明:

这是一个用string类的find和replace类方法实现字符串子串替换的程序,实现原理是find函数查找目标子串位置,replace函数实现子串替换,变量i记录当前位置

字串截取

实例:

#include <iostream>
using namespace std;

int main() {
	string s = "hello world code!";
	string k = " ";
	int i = 0, j = i;
	
	while(i < s.size()) {
		i = s.find(k, i);
		if(i == -1)	 i = s.size();
		cout<<s.substr(j, i - j)<<endl;
		i++;
		j = i;
	}
	//cout<<"this program is over";
	return 0;
} 

代码讲解:

这是一个在母串中截取子串的程序,substr函数的第一个参数j表示从位置j开始截取,第二个参数为目标子串的长度

插入与删除

插入:insert(pos,str)         //在pos位置插入字符串str

删除:erase(pos,size)        //从pos位置开始删除size位

转换

转换为字符串指针:

char* s = (char*)str.c_str();
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值