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風格字符串的一個非常不好的特徵,儘管它有好處,但總的來說弊大於利。