C++中對字符串進行插入、替換、刪除操作


#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;
	
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM