子串查找替换
示例:
#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();