C++ string 操作

#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;  
    // We can insert a str into a string

    //在字符串指定位置前面插入指定字符串的子串(从指定索引开始的指定个数的字符)  
    cout <<str1.insert(14,str2,2,9)<<endl;  
    // We can insert str into a str into a string

    //插入指定字符串的前n个字符  
    cout <<str1.insert(14,"test hello",5)<<endl;  
    // We can insert test str into a str into a string

    //插入n个相同字符到字符串中  
    cout <<str1.insert(14,6,'*')<<endl; 
    //We can insert ******test str into a str into a string

    //替换指定索引开始的指定长度的子串  
    cout <<str1.replace(3,3,"may")<<endl;
    // We may insert ******test str into a str into a string

    //用给定字符串的指定子串来进行替换  
    //如下,实际上使用的是could来进行替换,即由第4个字符开始,连续向后替换5个字符  
    cout <<str1.replace(3,3,"can could",4,5)<<endl;  
    // We could insert ******test str into a str into a string

    //使用给定字符串的前n个字符来进行替换:can  
    cout <<str1.replace(3,5,"can could",3)<<endl; 
    //We can insert ******test str into a str into a string

    //使用指定个数的重复字符来进行替换  
    cout <<str1.replace(3,3,5,'*')<<endl;  
    // We ***** insert ******test str into a str into a string

    string word="We";  
    size_t index=str1.find(word);  
    if(index!=string::npos)  
    //删除指定索引开始的指定长度的字符  
    cout <<str1.erase(index,word.length())<<endl;
    //  ***** insert ******test str into a str into a string

    return 0;  

}  
posted @ 2018-01-19 18:41  老耗子  阅读(78)  评论(0编辑  收藏  举报