引言:
在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类的常用成员函数
转载于:https://blog.51cto.com/qxzbgzh/525535