c++ primer 学习之路 (14) 4.3 string类简介 strcpy() strcat()

4.3 string类简介

string类使用起来比数组简单,同时提供了将字符串作为一种数据类型的表示方法。

要使用string类,必须在程序中包含头文件string。

在很多方面,使用string对象的方式与使用字符数组相同。

  • 可以使用C-风格字符串来初始化string对象。
  • 可以使用cin来将键盘输入存储到string对象中。
  • 可以使用cout来显示string对象。
  • 可以使用数组表示法来访问存储在string对象中的字符。

使用string类时,某些操作比使用数组时更简单。例如,不能将一个数组赋给另一个数

组,但可以将一个string对象赋给另一个string对象:

可以使用运算符+将两个string对象合并起来,还可以使用运算符+=将字符串附加到string对象的末尾。继续前面的代码,您可以这样

#include<iostream>
#include<climits>
#include<string>
using namespace std;
int main()
{
 string s1 = "penguin";
 string s2, s3;
 cout << "you can assign one string object to another:s2=s1\n";
 s2 = s1;
 cout << "s1 " << s1 << " s2 " << s2 << endl;
 cout << "you can assign a c_style string to the string object.\n";
 s2 = "buzzard";
 cout << "s2 " << s2 << endl;
 s3 = s1 + s2;
 cout << "s3" << s3 << endl;
 s1 += s2;
 cout << s1<<endl;
 s2 += "for a day";
 cout << s2;
 system("pause");
 return 0;
}


可以使用函数strcpy( )将字符串复制到字符数组中,使用函数strcat( )将字符串附加到字符数组末尾:



猜你喜欢

转载自blog.csdn.net/zhangfengfanglzb/article/details/80590092