C++中对字符串进行插入、替换、删除操作
随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)#include <iostream>#include <string>using std::cout;using std::endl;using std::string;...
·
随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main(void){
string str1="We can insert a string";
string str2="a str into ";
//在字符串指定位置前面插入指定字符串
cout <<str1.insert(14,str2)<<endl;
//在字符串指定位置前面插入指定字符串的子串(从指定索引开始的指定个数的字符)
cout <<str1.insert(14,str2,2,9)<<endl;
//插入指定字符串的前n个字符
cout <<str1.insert(14,"test hello",5)<<endl;
//插入n个相同字符到字符串中
cout <<str1.insert(14,6,'*')<<endl;
//替换指定索引开始的指定长度的子串
cout <<str1.replace(3,3,"may")<<endl;
//用给定字符串的指定子串来进行替换
//如下,实际上使用的是could来进行替换
cout <<str1.replace(3,3,"can could",4,5)<<endl;
//使用给定字符串的前n个字符来进行替换:can
cout <<str1.replace(3,5,"can could",3)<<endl;
//使用指定个数的重复字符来进行替换
cout <<str1.replace(3,3,5,'*')<<endl;
string word="We";
size_t index=str1.find(word);
if(index!=string::npos)
//删除指定索引开始的指定长度的字符
cout <<str1.erase(index,word.length())<<endl;
return 0;
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)