C++之string类库

string 类使用起来比数组简单,同时提供了将字符串作为一种数据类型的表示方法。使程序员能够像处理普通变量那样处理字符串。

1.以下代码显示了string对象与字符数组之间的相似与不同

#include
#include
using namespace std;
int main()
{
	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;
}

string类库的用法:

可以使用C风格来初始化string对象。

可以使用cin来将键盘输入存储到string对象中。

也可以使用cout来显示string对象。

同时也可以使用数组访问存储在string中的字符。

string与字符数组的主要区别:

  • string对象声明为简单变量,而不是数组。
  • 类设计的程序能够自动处理string的大小,这使得其与字符数组相比较,使用string更方便,更安全。

2.赋值,拼接,附加.

  • 不能将一个数组赋值给另一个数组,但是可以将一个string类对象赋值给另一个string类对象。
  • string可以用运算符+将两个string类对象合并起来,还可以使用运算符+=将字符串附加到string对象的末尾。

如下程序显示了string对象的赋值,拼接和附加。

#include
#include
using namespace std;
int main()
{
	string str1 = "penguin";
	string str2, str3;
	cout << "You can assign one string object to another:str2=str1\n";
	str2 = str1;
	cout << "str1=" << str1 << ",str2=" << str2 << endl;
	cout << "You can assign a C-Style string to a string object." << endl;
	str2 = "buzzard";
	cout << "str2=" << str2<#include
#include
#include
using namespace std;
int main()
{
	char charr1[20];
	char charr2[20] = "jaguar";
	string str1;
	string str2 = "panther";
	str1 = str2;
	strcpy_s(charr1, charr2);
	str1 += "paste";
	strcat_s(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;
}

4.string类I/O.

使用cin和运算符>>来将输入存储到string对象中,使用cout和运算符<<来显示string类对象,其句法与处理C风格字符串相同。但每次读取一行而不是一个单词时,使用的句法不同,如下程序:

#include
#include
#include
using namespace std;
int main()
{
	char charr[20];
	string str;
	cout<<"Length of string in charr before input;"<

你可能感兴趣的:(C++,c++)