C++基礎之string對象


一、string對象的基本使用

C++標准模板庫中提供了string數據類型,專門用於處理字符串。string是一個類,這個類型的變量稱為“string對象”

1、要在程序中使用string對象,必須在程序中包含頭文件string,即在程序的最前面,要加上如下語句:#include<string>

2、聲明一個string對象,與聲明普通變量是類似的,格式如下:string 變量名;

    string str1; //聲明string對象str1,值為空
    string city="Beijing"; //聲明string對象city,並使用字符串常量進行初始化
    string str2=city; //聲明string對象str2,並使用字符串變量進行初始化
    cout<<"str1="<<str1<<"."<<endl;
    cout<<city<<","<<str2<<endl;
    //還可以使用字符數組對string變量進行初始化。例如:
    char name[ ]="C++程序";
    string s1=name;
    //還可以聲明一個string對象數組,即數組中每個元素都是字符串。例如:
    string citys[ ]={"Beijing","Shanghai","Tianjin","Chongqing"};
    cout<<citys[1]<<endl; //輸出Shanghai,數組下標從0開始
    cout<<sizeof(citys)/sizeof(string)<<endl; //輸出數組元素個數
    sizeof(string);//是每個string對象的大小,所以sizeof(citys)/sizeof(string)表示的是數組元素個數。

1、字符串的連接: +號

    string  s2="C++";
    string s3="C";
    cout<<"s2= "<<s2<<endl;//s2= C++
    cout<<"s3= "<<s3<<endl;//s3= C
    cout<<s3+s2<<endl; //CC++

2、字符串判斷空:empty()

    string str; //未初始化,空串
    if(str.empty()){
        cout<<"str is NULL."<<",length="<<str.length()<<endl;//str is NULL.,length=0
    } else{
        cout<<"str is not NULL."<<endl;
    }

3、字符串的追加:append()

    string str; //未初始化,空串
    str=str.append("ABC").append("DEFG");
    cout<<"str is "<<str<<",size="<<str.size()<<endl;//str is ABCDEFG,size=7

4、字符的查找:find()

    string str; //未初始化,空串
    str=str.append("ABC").append("DEFG");
    cout<<"str is "<<str<<",size="<<str.size()<<endl;//str is ABCDEFG,size=7
    const char *p=str.c_str();
    cout<<"*p="<<*p<<endl;//*p=A
    cout<<"p="<<p<<endl;//p=ABCDEFG
    //1、find 函數 返回jk 在s 中的下標位置
    cout<<"find:"<<str.find("D")<<endl; //查找成功,find:3
    cout<<"find:"<<str.find("F")<<endl; //查找成功,find:5
    //2、返回子串出現在母串中的首次出現的位置,和最后一次出現的位置。
    cout<<"find_first_of:"<< str.find_first_of("A")<<endl;//find_first_of:0
    cout<<"find_last_of:"<< str.find_last_of("A")<<endl;//find_last_of:0
    //3、查找某一給定位置后的子串的位置
    //從字符串str 下標4開始,查找字符串D ,返回D 在str 中的下標
    cout<<"find:"<<str.find("D",4)<<endl; //查找失敗:find:4294967295
    //從字符串str 下標0開始,查找字符串F ,返回F 在str 中的下標
    cout<<"find:"<<str.find("F",0)<<endl; //查找成功,find:5

5、字符的插入:insert()

    string str; //未初始化,空串
    str=str.append("ABC").append("DEFG");
    //4、字符串的插入
    string str1=str.insert(4,"123");//從下標4的位置插入
    cout<<str1<<endl;//ABCD123EFG

 


免責聲明!

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



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