一、獲取字元串長度
C++ string庫中提供了length和size函數用於獲取字元串的長度,返回值類型都是size_t,示例代碼如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
cout << "Length: " << str.length() << endl;
cout << "Size : " << str.size() << endl;
return 0;
}
輸出結果:
Length: 11 Size : 11
二、字元串查找
string庫中提供了多種函數用於查找字元串中特定字元或子字元串的位置,其中常用的是find函數和rfind函數。find函數從字元串的頭部開始查找,rfind函數從字元串的尾部開始查找,兩個函數都返回第一個匹配字元串的位置,如果沒有找到則返回string::npos。示例代碼如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
int pos1 = str.find("l");
int pos2 = str.rfind("l");
int pos3 = str.find("World");
int pos4 = str.find("world");
cout << "pos1: " << pos1 << endl;
cout << "pos2: " << pos2 << endl;
cout << "pos3: " << pos3 << endl;
cout << "pos4: " << pos4 << endl;
return 0;
}
輸出結果:
pos1: 2 pos2: 9 pos3: 6 pos4: -1
三、字元串替換
string庫中提供了replace函數用於替換字元串中的某個子串。該函數的參數包括被替換子串的位置、長度和替換字元串,示例代碼如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
str.replace(6, 5, "Li Lei");
cout << str << endl;
return 0;
}
輸出結果:
Hello Li Lei
四、字元串截取
string庫中提供了substr函數用於從字元串中截取一部分。該函數的參數包括起始位置和截取長度,如果不提供截取長度則默認截取到字元串末尾。示例代碼如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
string sub1 = str.substr(3, 5);
string sub2 = str.substr(6);
cout << sub1 << endl;
cout << sub2 << endl;
return 0;
}
輸出結果:
lo Wo World
五、字元串拼接
string庫中提供了多種方式用於字元串的拼接,其中常用的是+運算符和append函數。+運算符用於將兩個字元串連接起來,append函數用於在字元串末尾追加另一個字元串。示例代碼如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello ";
string str2 = "World";
string str3 = str1 + str2;
string str4 = str1.append(str2);
cout << str3 << endl;
cout << str4 << endl;
return 0;
}
輸出結果:
Hello World Hello World
六、字元串分割
對於需要將字元串按照指定字元分割成多個子串的場景,可以使用stringstream類和getline函數。示例代碼如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str = "apple,banana,orange";
stringstream ss(str);
string item;
while (getline(ss, item, ',')) {
cout << item << endl;
}
return 0;
}
輸出結果:
apple banana orange
以上就是使用C++ string函數實現字元串相關操作的相關內容。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254659.html
微信掃一掃
支付寶掃一掃