String类

在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

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-18 20:28  贱贱的梦想  阅读(135)  评论(0编辑  收藏  举报