C++string类简介
之前,我们讲过有两种表示字符串常量的方法,一种是char数组,另一只就是使用string类对象来表示字符串常量。现在我们来介绍一下如何使用string类对象。
首先,使用string类对象之前,需要包含一个头文件string,string类位于std命名空间中,所以需要使用using指令,或者是使用std::string来引用它。这里我们通过一组代码来了解关于char数组和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:\n";cout<<charr1<<" "<<charr2<<" "<<str1<<" "<<str2<<endl;cout<<"The third letter in "<<charr2<<" is "<<charr2[2]<<endl;cout<<"The third letter in "<<str2<<" is "<<str2<<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 in jaguar is g
The third letter in panther is n
从这个示例可知,在很多方面,使用string对象的方式与使用字符数组相同。
1)可以使用C风格字符串来初始化string对象
2)可以使用cin来将键盘输入储存到string对象中
3)可以使用cout来显示string对象
4)可以使用数组表示法来访问储存在string对象中的字符
区别在于:可以将string对象声明为简单变量而不是数组。
类设计让程序能够自动处理string的大小,这使得使用string对象比使用字符数组更加的方便,同时也更加的安全。
所以对于新手来说,使用string对象对于新手更加友好,也更方便。