1. 程式人生 > 其它 >C++string字串拼接遇到的問題

C++string字串拼接遇到的問題

C++ 字串拼接

最初嘗試

//目的: 把字串student_ 和A拼接起來
string nameseed = "ABCDE";
string name;
name="student_" +nameseed[0];
cout<<"拼接後的字串:"<<name<<endl;

輸出:拼接後的字串:ange執行結果

再次嘗試

方法1

string nameseed = "ABCDE";
string name;
name = std::string("student_")
+ nameseed[0]; cout<<"拼接後的字串:"<<name<<endl;

輸出:拼接後的字串:student_A在這裡插入圖片描述

方法2

string nameseed = "ABCDE";
string name;
name = "student_";
name += nameseed[0];
cout << "拼接後的字串:" << name << endl;


輸出:拼接後的字串:student_A在這裡插入圖片描述

總結

對於string類變數,我們可以直接用“+”或者“+=”進行字串的連線。

用“+”進行字串連線時,操作符左右兩邊既可以都是string類變數,也可以是一個string類變數和一個C風格的字串,還可以是一個string字串和一個char型字元。

用“+=”進行字串連線時,操作符右邊既可以是一個string字串,也可以是一個C風格字串或一個char型字元。

上述兩種方法:左邊必須是string類字串。

string類字串進行連線時,c++中預設"student_"字串為char*型,而不是我們想象中的string類變數,而"student_"又處在等式的最左邊,所以並沒有實現我們想要的目的。