在程序设计中,字符串常常是不可避免的。其中,判断字符串是否包含另一个字符串是经常使用到的功能。在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/n/368047.html