您好,登錄后才能下訂單哦!
在C++中,std::string
類有一個(gè)非常有用的成員函數(shù)叫做find
,它可以在字符串中查找子字符串的位置。如果找到了子字符串,find
函數(shù)會(huì)返回子字符串第一次出現(xiàn)的位置的索引;如果沒(méi)有找到子字符串,find
函數(shù)會(huì)返回std::string::npos
。
以下是一個(gè)使用std::string::find
函數(shù)的示例代碼:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string sub = "world";
size_t pos = str.find(sub);
if (pos != std::string::npos) {
std::cout << "Found '" << sub << "' at position " << pos << std::endl;
} else {
std::cout << "'" << sub << "' not found" << std::endl;
}
return 0;
}
在這個(gè)示例中,我們?cè)谧址?code>"Hello, world!"中查找子字符串"world"
,并使用std::string::find
函數(shù)找到它的位置。然后,我們輸出子字符串的位置。
需要注意的是,std::string::find
函數(shù)是區(qū)分大小寫的。如果你想進(jìn)行不區(qū)分大小寫的查找,可以在查找之前將字符串和子字符串都轉(zhuǎn)換為小寫(或大寫):
#include <algorithm>
#include <cctype>
// ...
size_t pos = str.find(sub);
if (pos != std::string::npos) {
std::cout << "Found '" << sub << "' at position " << pos << std::endl;
} else {
std::cout << "'" << sub << "' not found" << std::endl;
}
// Convert both strings to lowercase to perform case-insensitive search
transform(str.begin(), str.end(), str.begin(), ::tolower);
transform(sub.begin(), sub.end(), sub.begin(), ::tolower);
pos = str.find(sub);
if (pos != std::string::npos) {
std::cout << "Found '" << sub << "' at position " << pos << std::endl;
} else {
std::cout << "'" << sub << "' not found" << std::endl;
}
在這個(gè)修改后的示例中,我們使用std::transform
函數(shù)和::tolower
函數(shù)將字符串和子字符串都轉(zhuǎn)換為小寫,然后再次使用std::string::find
函數(shù)進(jìn)行查找。這樣就可以實(shí)現(xiàn)不區(qū)分大小寫的查找了。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。