1. 程式人生 > >C++字串的插入、替換與刪除的實現

C++字串的插入、替換與刪除的實現

 具體實現程式碼如下

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
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;
	
}

輸出結果:

We can insert a str into a string We can insert str into a str into a string We can insert test str into a str into a string We can insert ******test str into a str into a string We may insert ******test str into a str into a string We could insert ******test str into a str into a string We can insert ******test str into a str into a string We ***** insert ******test str into a str into a string  ***** insert ******test str into a str into a string