c++ string 類基本用法範例

來源:互聯網
上載者:User

#include <string>    //  使用 string 類時須包含這個檔案
#include <iostream>

 

using namespace std;

int main()
{
    string str1;
   
    //  輸入與輸出
    cout << "輸入字串 str1" << endl;
    cin >> str1; getchar();
    cout << str1 << endl << endl << endl;
    
    //  一行行讀取 
    cout << "輸入字串 str1" << endl;
    getline( cin, str1 );
    cout << str1 << endl;

    //  與 c字元轉換
    string str2("Hello World!"), str3;
    char   str4[50];

    cout << "輸入 C 字串" << endl;
    scanf("%s",str4);
    str3= str4;

    cout << "str2 is " << str2 << endl;
    cout << "str3 is " << str3 << endl << endl << endl;

    //  求字串的長度
    string str5;
    cout << "輸入字串 str5" << endl;
    cin >> str5;
    int   len= str5.size();
    cout << "字串 str5的長度為" << len << endl << endl << endl;

    //  遍曆字串例子
    string str6;
    cout << "輸入字串 str6" << endl;
    cin >> str6;
    int i;
    for( i= 0; i< str6.size(); ++i )
    cout << str6[i];
    cout << endl << endl;

    //  比較兩個字串   比較規則同 c字串比較規則
    string str7, str8;
    cout << "輸入字串 str7, str8 , 中間用空格格開" << endl;
    cin >> str7 >> str8;

    if( str7< str8 ) cout << str7 << "  小於 " << str8 << endl;
    else if( str7> str8 ) cout << str7 << "  大於 " << str8 << endl;
    else cout << str7 << "  等於 " << str8 << endl;
    
    
    //  字串與字元相加 
    string str9= "Darren";
    char ch1= 'a', ch2= 'b';
    str9= str9+ ch1; cout << str9 << endl << endl;
    str9= ch2+ str9; cout << str9 << endl << endl << endl;
    
    //  字串與字串相加
    string str10= "Acm", str11= "ICPC";
    str10.append( str11 );
    cout << str10 << endl << endl;
    
    //  字串是否包含子串  如果包含 則返回子串在目標串中第一次出現的位置 
    string str12= "I am a student", str13= "student", str14= "aaaaaaa";
    if( str12.find( str13 )!= -1 )  cout << "Find " << str13 << endl;
    if( str12.find( str14 )== -1 )  cout << "Not Find  " << str14 << endl;
    
    //  轉換成 c_字串
    string str15= "Hello World";
    printf("%s\n", str15.c_str() );
     
    system("pause"); 

    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.