引言:
在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;
cout<<"length of s2:"<<s2.length()<<endl;
return 0;
}
【知識點】
1.string類的操作符
2.string類的常用成員函數