在程序設計中,字符串常常是不可避免的。其中,判斷字符串是否包含另一個字符串是經常使用到的功能。在C++編程語言中,string類提供了多種方法判斷字符串包含的方式。本篇文章將會詳細介紹如何使用string類中的包含方法。
一、string類中包含方法的概述
在string類中,包含方法主要有以下幾個:
- find()
- rfind()
- find_first_of()
- find_last_of()
- find_first_not_of()
- find_last_not_of()
這些方法都返回一個整數類型值,表示查找到的字符串的位置。如果返回-1,則表示未查找到。
二、find()方法
find()方法是最基本的查找方法,它可以在一個字符串中查找特定的子字符串。此方法有兩個參數,第一個是要查找的字符串,第二個是要查找的起始位置。
// 示例代碼1
string str = "hello world";
int pos = str.find("world");
if(pos != -1) {
cout << "world在字符串中的位置為:" << pos << endl;
}
// 示例代碼2
string str = "hello world";
int pos = str.find("o", 5); // 在索引為5以後的位置開始查找字符'o'
if(pos != -1) {
cout << "'o'在字符串中的位置為:" << pos << endl;
}
三、rfind()方法
rfind()方法與find()方法類似,只不過是從字符串的末尾往前查找。
// 示例代碼
string str = "hello world";
int pos = str.rfind("l");
if(pos != -1) {
cout << "最後一個'l'在字符串中的位置為:" << pos << endl;
}
四、find_first_of()方法和find_last_of()方法
find_first_of()方法和find_last_of()方法都是用於查找目標字符串中包含的一組字符的第一個或最後一個出現的位置。
// 示例代碼1
string str = "hello world";
int pos = str.find_first_of("ow");
if(pos != -1) {
cout << "'o'或'w'在字符串中的第一個位置為:" << pos << endl;
}
// 示例代碼2
string str = "hello world";
int pos = str.find_last_of("lo");
if(pos != -1) {
cout << "'l'或'o'在字符串中的最後一個位置為:" << pos << endl;
}
五、find_first_not_of()方法和find_last_not_of()方法
find_first_not_of()方法和find_last_not_of()方法都是用於查找一個字符集之外的字符。
// 示例代碼1
string str = "hello world";
int pos = str.find_first_not_of("hel"); // 查找第一個不是'h'、'e'、'l'的字符
if(pos != -1) {
cout << "第一個不是'h'、'e'、'l'的字符在字符串中的位置為:" << pos << endl;
}
// 示例代碼2
string str = "hello world";
int pos = str.find_last_not_of("dlro"); // 查找最後一個不是'd'、'l'、'r'、'o'的字符
if(pos != -1) {
cout << "最後一個不是'd'、'l'、'r'、'o'的字符在字符串中的位置為:" << pos << endl;
}
總結
本篇文章詳細介紹了string類中的包含方法,並針對每一個方法給出了示例代碼。在實際編程中,應根據具體的需求選擇合適的包含方法,並結合其他方法進行字符串處理,以達到更好的編程效果。
原創文章,作者:WHGLG,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/368047.html