ISO/ANSI C++98标准通过添加string类扩展了C++库,因此现在可以string类型的变量(使用C++的话说是对象)而不是字符数组来存储字符串
要使用string类,必须在程序中包含头文件string。string类位于名称空间std中,因此您必须提供一条using编译指令,或者使用std::string来引用它。string类定义隐藏了字符串的数组性质,让您能够像处理普通变量那样处理字符串。
#include<iostream>
#include<string>
int main(){
using namespace std;
char charr1[20];
char charr2[20]="jaguar";
string str1;
string str2="panther";
cout<<"Enter a kind of feline ";
cin>>charr1;
cout<<"Enter another kind of feline ";
cin>>str1;
cout<<"Here are some felines"<<endl;
cout<<charr1<<" "<<charr2<<" "<<str1<<" "<<str2<<endl;
cout<<"The third letter in"<<charr2<<" is "
<<charr2[2]<<endl;
cout<<"The third letter in"<<str2<<" is "
<<str2[2]<<endl;
return 0;
}
输出:
Enter a kind of feline ocelot
Enter another kind of feline tiger
Here are some felines
ocelot jaguar tiger panther
The third letter injaguar is g
The third letter inpanther is n
由程序可知 在很多方面,使用string对象的方式与使用字符数组相同
使用string对象的方式与使用字符数组相同。
可以使用C-风格字符串来初始化string对象。
可以使用cin来将键盘输入存储到string对象中。
可以使用cout来显示string对象。
可以使用数组表示法来访问存储在string对象中的字符。
string对象和字符数组之间的主要区别是,可以将string对象声明为简单变量,而不是数组:
C++11也允许将列表初始化用于C-风格字符串和string对象:
char first_date[] = {“Le Chapon Dodu”};
string类的其他操作
在C++新增string类之前,程序员也需要完成诸如给字符串赋值等工作。对于C-风格字符串,程序员使用C语言库中的函数来完成这些任务。头文件cstring(以前为string.h)提供了这些函数
可以使用函数strcpy( )将字符串复制到字符数组中,使用函数strcat( )将字符串附加到字符数组末尾:
#include <iostream>
#include <cstring>
int main()
{
using namespace std;
char charr1[20];
char charr2[20] = "jaguar";
string str1;
string str2 = "panther";
str1=str2;
strcpy(charr1,charr2);
str1+=" paste";
strcat(charr1," juice");
int len1=str1.size();
int len2=strlen(charr1);
cout<<"The string "<<str1<< " contains "<<len1<< " characters"<<endl;
cout<<"The string "<<charr1<<" contains "<<len2<<" characters"<<endl;
return 0;
}
输出:
The string panther paste contains 13 characters
The string jaguar juice contains 12 characters
函数strlen( )是一个常规函数,它接受一个C-风格字符串作为参数,并返回该字符串包含的字符数。函数size( )的功能基本上与此相同,但句法不同:str1不是被用作函数参数,而是位于函数名之前,它们之间用句点连接