1. 程式人生 > >《C++語言程式設計基礎》學習之字串

《C++語言程式設計基礎》學習之字串

在c++中不建議繼續使用C語言風格的陣列字串,都使用字串類string表示字串,string實際上是對字元陣列操作的封裝string類常用的建構函式 string(); //預設建構函式,建立一個長度為0的串,例:string s1; string(const char *s); //用指標s所指向的字串常量初始化string物件,例:string s2 = “abc”; string(const string& rhs); //複製建構函式,例:string s3 = s2;string類常用操作 s + t 將串s和t連線成一個新串 s = t 用t更新s s == t 判斷s與t是否相等 s != t 判斷s與t是否不等 s < t 判斷s是否小於t(按字典順序比較) s <= t 判斷s是否小於或等於t (按字典順序比較) s > t 判斷s是否大於t (按字典順序比較) s >= t 判斷s是否大於或等於t (按字典順序比較) s[i] 訪問串中下標為i的字元

string s1 = "abc", s2 = "def";
string s3 = s1 + s2; //結果是"abcdef"
bool s4 = (s1 < s2); //結果是true
char s5 = s2[1]; //結果是'e'
inline void test(const char *title, bool value) {
	cout << title << " returns " << (value ? "true" : "false") << endl;
}
int main(){
	string s1 = "DEF";
	cout << "s1 is " << s1 << endl;
	string s2;
	cout << "Please enter s2: ";
	cin >> s2;
	cout << "length of s2: " << s2.length() << endl;

	//比較運算子的測試
	test("s1<=\"ABC\"", s1 <= "ABC");
	test("\"DEF\"<=s1", "DEF" <= s1);

	//連線運算子的測試
	s2 += s1;
	cout << "s2=s2+s1: "<< s2 << endl;
	cout << "length of s2: " << s2.length() << endl;
	return 0;
}

如何輸入整行字串? 用cin的>>操作符輸入字串,會以空格作為分隔符,空格後的內容會放在鍵盤緩衝區,下一回輸入時被讀取 輸入整行字串 getline可以輸入整行字串(要包string標頭檔案),例如:getline(cin, s2); 輸入字串時,可以使用其它分隔符作為字串結束的標誌(例如逗號、分號),將分隔符作為getline的第3個引數即可, 例:getline(cin, s2, ',');

int main(){
	for (int i = 0; i < 2; i++) {
		string city, state;
		getline(cin, city, ',');
		getline(cin, state);
		cout << "City:" << city << " State:" << state << endl;
	}
	return 0;
}

執行的結果: Beijing,China City: Beijing State: China San Francisco,the United States City: San Francisco State: the United States