您的位置:首页 > 其它

String类

2015-08-18 20:28 302 查看
在C++中,要使用 string 类,必须在程序中包含头文件string。string 类位于名称空间 std 中,因此必须提供一条 using 编译指令,或者使用 std::string 来引用它。

string类定义隐藏了字符串的数组性质,能够像处理普通变量那样处理字符串。通过以下程序可以说明 string 对象和字符数组之间的一些相同点和不同点。

例:

// strtype1.cpp -- using the C++ string class
#include <iostream>
#include <string> // make string class available
int main()
{
using namespace std;
char charr1[20]; // create an empty array
char charr2[20] = "jaguar"; // create an initialized array
string str1; // create an empty string object
string str2 = "panther"; // create an initialized string
cout << "Enter a kind of feline: ";
cin >> charr1;
cout << "Enter another kind of feline: ";
cin >> str1; // use cin for input
cout << "Here are some felines:\n";
cout << charr1 << " " << charr2 << " "
<< str1 << " " << str2 // use cout for output
<< endl;
cout << "The third letter in " << charr2 << " is "
<< charr2[2] << endl;
cout << "The third letter in " << str2 << " is "
<< str2[2] << endl; // use array notation
return 0;
}


运行结果:



参考资料:
《 C++ Primer Plus (第6版)中文版 》P82-83
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: