天天看點

string類

引言:

在c語言裡,使用字元數組來存儲字元串;同樣在c++裡也可以如此,但是同時,c++提供了字元串的封裝類——string類,與c語言裡的使用數組存儲字元串,通過調用系統函數處理字元串(使用時,包含頭檔案cstring)這種資料存儲和資料處理函數分離的方式相比,顯然string類比以前友善了許多。

源程式:

#include "stdafx.h"

#include<iostream>

#include<string>  //頭檔案為一個封裝類

using namespace std;

//測試函數

void test(const char *title,bool value){

 cout<<title<<" returns "<<(value?"true":"false")<<endl;

}

int _tmain(int argc, _tchar* argv[])

{

 string s1="def";

 cout<<"s1 is:"<<s1<<endl;

 string s2;

 cout<<"please enter s2:";

 cin>>s2;

 cout<<"length of s2:"<<s2.length()<<endl;

 //測試比較操作符

 test("s1<=\"abc\"",s1<="abc");

 test("\"def\"<=s1","def"<=s1);

 //測試連接配接操作符

 s2+=s1;

 cout<<"s2+=s1: "<<s2<<endl;

 return 0;

【知識點】

1.string類的操作符

2.string類的常用成員函數