一、字元串的拼接
string類提供了兩種方式來進行字元串的拼接操作,一種是使用「+」運算符,另一種是使用成員函數append()。
使用「+」運算符
string str1 = "Hello ";
string str2 = "world!";
string str3 = str1 + str2;
在以上代碼中,通過使用「+」運算符,將str1與str2拼接起來,並將結果存儲在str3中。這個方法的優點是簡單易懂,但是當需要拼接的字元串較多時,使用「+」操作符可能會產生一些性能問題。
使用成員函數append()
string str1 = "Hello ";
string str2 = "world!";
str1.append(str2);
在以上代碼中,通過使用成員函數append(),將str2拼接到了str1的尾部。這個方法的優點是可以拼接任意數量的字元串,而且效率較高。
二、字元串的比較
string類提供了多種方式進行字元串的比較,包括「==」、「!=」、「」、「=」等運算符,以及成員函數compare()。
使用運算符
string str1 = "apple";
string str2 = "banana";
bool result = (str1 == str2);
在以上代碼中,使用「==」運算符比較了兩個字元串的內容,然後將結果存儲在了result變數中。
使用成員函數compare()
string str1 = "apple";
string str2 = "banana";
int result = str1.compare(str2);
在以上代碼中,使用成員函數compare()比較了兩個字元串的內容,返回的結果可以分為三種情況:
- 如果str1等於str2,返回0;
- 如果str1小於str2,返回一個負數;
- 如果str1大於str2,返回一個正數。
三、字元串的查找
string類提供了多種方法進行字元串的查找,包括成員函數find()、rfind()、find_first_of()、find_last_of()等。
使用成員函數find()
string str = "hello world";
int pos = str.find("world");
在以上代碼中,使用成員函數find()查找了子串「world」在字元串中第一次出現的位置,並將結果存儲在了pos變數中。如果沒有找到,會返回string::npos。
使用成員函數rfind()
string str = "hello world";
int pos = str.rfind("o");
在以上代碼中,使用成員函數rfind()查找字元「o」在字元串中最後一次出現的位置,並將結果存儲在了pos變數中。如果沒有找到,會返回string::npos。
使用成員函數find_first_of()
string str = "hello world";
int pos = str.find_first_of("aeiou");
在以上代碼中,使用成員函數find_first_of()查找字元串中第一個母音字母的位置,並將結果存儲在了pos變數中。如果沒有找到,會返回string::npos。
使用成員函數find_last_of()
string str = "hello world";
int pos = str.find_last_of("aeiou");
在以上代碼中,使用成員函數find_last_of()查找字元串中最後一個母音字母的位置,並將結果存儲在了pos變數中。如果沒有找到,會返回string::npos。
四、字元串的替換
string類提供了成員函數replace()進行字元串的替換操作,其語法為:
string& replace(size_t pos, size_t len, const string& str);
其中,pos表示要開始替換的位置,len表示要替換的子串的長度,str表示用來替換的字元串。
使用成員函數replace()
string str = "hello world";
str.replace(0, 5, "hi");
在以上代碼中,通過使用replace()函數,將字元串「hello」替換成了「hi」,得到了新的字元串「hi world」。
五、字元串的分割
string類本身並沒有提供字元串的分割函數,但是可以結合sstream頭文件中的stringstream類進行字元串的分割。
使用stringstream類進行字元串的分割
string str = "apple,banana,orange";
stringstream ss(str);
string temp;
vector vec;
while (getline(ss, temp, ',')) {
vec.push_back(temp);
}
在以上代碼中,首先將字元串str放入了一個stringstream對象中,然後使用getline()函數和逗號為分隔符將字元串分割成若干子串,並將它們存儲在了vector容器中。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/270706.html