一、獲取字符串長度
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-hk/n/254659.html
微信掃一掃
支付寶掃一掃