本章演示如何操作C++文本字符串:字符數(shù)組的更簡單、更強(qiáng)大的替代。
創(chuàng)建字符串變量
與char、int、float、double和bool數(shù)據(jù)類型不同,C++中沒有原生的"字符串"數(shù)據(jù)類型--但是它的庫類提供了字符串對(duì)象,用來模擬字符串?dāng)?shù)據(jù)類型。為了使程序能夠使用它,必須在程序開始時(shí)用#include指令添加該庫。像類庫一樣,庫也是std命名空間的一部分,它被C++標(biāo)準(zhǔn)庫類所使用。這意味著字符串對(duì)象可以被稱為std::string,或者在程序開始時(shí)包含using namespace std;指令時(shí)更簡單地稱為string。字符串變量可以通過在變量名后面的圓括號(hào)中加入一個(gè)文本字符串來初始化。在C++中,文本字符串必須始終包含在""雙引號(hào)字符中--""單引號(hào)只用于包圍char數(shù)據(jù)類型的字符值。與C語言程序員必須使用的char數(shù)組相比,C++字符串變量更容易操作,因?yàn)樗梢宰詣?dòng)調(diào)整大小以適應(yīng)任何文本字符串的長度。在較低的層次上,文本仍然是例如句子,可以使用getline函數(shù)。這個(gè)函數(shù)需要兩個(gè)參數(shù)來指定字符串的來源和目的地。例如,其中cin函數(shù)是源,名為"str"的字符串變量是目的地。getline(cin,str)。getline函數(shù)從輸入"流"中讀出,直到遇到行末的換行符--當(dāng)你點(diǎn)擊Return時(shí)產(chǎn)生。在混合使用cin和getline函數(shù)時(shí)必須注意,因?yàn)間etline函數(shù)會(huì)自動(dòng)讀取輸入緩沖區(qū)中的任何內(nèi)容--給人以程序跳過一條指令的印象。cin.ignore函數(shù)可以用來克服這個(gè)問題,它忽略了留在輸入緩沖區(qū)的內(nèi)容。#include
#include
using namespace std;
int main{
string name;
cout << "Please enter your full name: ";
cin >> name;
cout << "Welcome " << name << endl;
cout << "Please re-enter your full name: ";
// Uncomment the next line to correct this program.
// cin.ignore(256, '\n');
getline(cin, name);
cout << "Thanks, " << name << endl;
return 0;
}
cin.ignore函數(shù)的參數(shù)指定它最多應(yīng)丟棄256個(gè)字符,并在遇到換行符時(shí)停止。字符串轉(zhuǎn)換
convert.cpp
#include
#include
#include
using namespace std;
int main(){
string term = "100"; // String to convert to int.
int number = 100; // Int to convert to string.
string text; // String variable for converted int.
int num; // Int variable for converted string.
stringstream stream; // Intermediate stream object. // Convert string to int.
stream << term; // Load string int ostream.
stream >> num; // Extract stream to int.
num /= 4; // Manipulate the int.
cout << "Integer value: " << num << endl;
cout << "Integer value: " << stoi(term) << endl; // Reset the stream object back to new.
stream.str(""); // Reset the stream to an empty string.
stream.clear(); // Reset the stream bit flags (good, bad, eof, fail).
// Convert int to string.
stream << number; // Load int int ostream.
stream >> text; // Extract stream to string.
text += "PerCent"; // Manipulate the string.
cout << "String value: " << text << endl;
cout << "Integer value: " << to_string(number) << endl;
return 0;
}
符串的特性
C++庫提供了許多函數(shù),使我們可以輕松地處理字符串。與char數(shù)組不同,字符串變量會(huì)動(dòng)態(tài)放大以容納分配給它的字符數(shù),它當(dāng)前的內(nèi)存大小可以通過庫的capacity函數(shù)來顯示。一旦放大,分配的內(nèi)存大小將保持不變,即使有更小的字符串被分配給該變量。features.cpp
#include
#include
using namespace std;
void computeFeatures(string);
int main{
string text = "C++ is fun";
computeFeatures(text);
text += " for everyone";
computeFeatures(text);
text = "C++ Fun";
computeFeatures(text);
text.clear();
computeFeatures(text);
return 0;
}
void computeFeatures(string text){
cout << endl << "String: " << text << endl;
cout << "Size: " << text熱點(diǎn):比特幣字符 GO語言 比特幣指南 nft指南 幣圈指南