C++ string 类简介
使用 string 类,必须在程序中包含头文件 string 。string 类位于名称空间 std 中。string 类定义隐藏了字符串的数组性质,可以让我们像处理变量那样处理字符串。
以下使用了 C++ Primer Plus 中的例子:
// 比较 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[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 in jaguar is g
The third letter in panther is n
可以知道,很多方面 string 对象方式和字符数组相同。但是 string 要方便许多。
如何定义一个字符串?
string 变量名 = "内容’;
例子:
string s1 = "Hello!";
C++ string 类隐藏了字符串的数组特性,提供了更方便的字符串操作。通过包含头文件 string,我们可以使用 std 名称空间中的 string 类。示例展示了如何定义和使用 string 对象,如打印和获取字符串的特定字符。

1215

被折叠的 条评论
为什么被折叠?



