天天看点

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类的常用成员函数