C风格的字符串的主要缺点是:声明比较复杂,容易踩坑。作为面向对象的经典语言C++,也有其对应的字符串功能。得益于强大的类,C++风格的字符串非常简洁,而且很多功能都封装在这个类中,使用起来非常方便。
C++的字符串类名为string
,以下从类对象的创建、字符串的输入、字符串的连接、字符串的拷贝、读取字符串的长度来进行程序演示。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sgreet ("Hello std::string");
cout << sgreet << endl;
cout << "Enter a line of string:" << endl;
string sfirstLine;
getline(cin, sfirstLine);
cout << "Enter another:" << endl;
string ssecondLine;
getline(cin, ssecondLine);
cout << "Result of connection:" << endl;
string sconnection = sfirstLine + " " + ssecondLine;
cout << sconnection << endl;
cout << "Copy of string:" << endl;
string scopy;
scopy = sconnection;
cout << scopy << endl;
cout << "Length of connection string: " << sconnection.length() << endl;
return 0;
}
运行结果:
可以看到,C++的字符串结尾并没有空字符
,个人觉得空字符
是C风格字符串的一个非常不好的特征,尽管它有好处,但总的来说弊大于利。