C++学习笔记系列2-31

字符串查找

**想在一串字符串中进行目标字符串,或者字符的查找,可以使用 find( ) 和 rfind( ),前者是从左向右查,后者是从右向左查,方向相反。如果找到目标则返回该目标的索引值,也就是它的位置编号;如果没有找到,则返回常量:string::npos。**如果想输出这个值,可能是 "-1",但是我们不必纠结它的值,一般情况下我们不会用这个值,而是将 string::npos 作为 if 语句的判断条件。

#include <iostream>

#include <string>

using namespace std;

int main()

{

string str1 = "hello_world";

// 对 str1 中的 "llo" 这段字符串进行 "从左向右" 和 "从右向左" 的查找,并返回索引值

// 字符串:h e l l o _ w o r l d

// 索引号:0 1 2 3 4 5 6 7 8 9 10

int F_index = str1 . find( "o" ); // F代表从前向后

cout << "从左向右查询,"o"的index值为:" << F_index <<endl;

int B_index = str1 . rfind( "o" );// B代表从后向前

cout << "从右向左查询,"o"的index值为:" << B_index <<endl;

// 还可以在声明 2 个字符串,用于另一种形式的查找,如:

string str2 = "wor";

string str3 = "abc";

int index2 = str1 . find ( str2 ); // str2 的内容 str1 中有,因此会返回索引值

int index3 = str1 . find ( str3 ); // str3 的内容 str1 中没有,因此会返回:npos

if( index2 != string::npos )

cout << "查找的字符串位置是:" << index2 <<endl;

else

cout << "没有找到对应的字符串。" << endl;

if( index3 != string::npos )

cout << "查找的字符串位置是:" << index3 <<endl;

else

cout << "没有找到对应的字符串。" << endl;

}

输出: 从左向右查询,"o"的index值为:4

从右向左查询,"o"的index值为:7

查找的字符串位置是:6

没有找到对应的字符串。

从前两个输出可以看出,find和rfind在查找相同的字符串时,则是以"就近原则"执行,本案例中,字符串里有 2 个 o,从前找,索引号为:4,从后找,索引号为:7,只要找到了就停止查找了,所以在使用查找函数时,要注意是否会有相同字符。

后两个输出,我们可以看到 string::npos 它的用处,它可以作为判断条件进行if语句的判断,很多时候都是通过这个方式使用的。