C ++のString.find()およびstring :: npos(analysis)



String Find String



string.find()およびstring :: npos

文字列str1に文字列str2があるかどうかを判断する場合。

string str1='abcdefg' string str2='abc' Misunderstanding1if(str1.find(str2)) return true //Incorrect //If str2 is not found, it will return -1, at this time if will still be executed (-1 is not 0, and if conditions are met) correct: if(str1.find(str2) != string::npos) return true //correct //By default, start from the subscript 0 of the string str1, search for the string str2, and return the subscript of str2 in str1 cout<<str1.find(str2)<<endl Output:0

str1.find(str2、5)



//Start from the string str1 subscript 5, find the string str2, and return the subscript of str2 in str1 string str1='abcdefg' string str2='abc' pos=str1.find(str2,5) cout<<pos<<endl

他のあまり一般的に使用されない検索関連関数:

//find function returns the subscript position of any character in flag for the first occurrence in s flag = 'c' position = s.find_first_of(flag) cout << 's.find_first_of(flag) is : ' << position << endl //Start from string s subscript 5, find string b, and return the subscript of b in s position=s.find('b',5) cout<<'s.find(b,5) is : '<<position<<endl //Find all positions where flag appears in s. flag='a' position=0 int i=1 while((position=s.find_first_of(flag,position))!=string::npos) { //position=s.find_first_of(flag,position) cout<<'position '<<i<<' : '<<position<<endl position++ i++ } //Find the first position that does not match s in the flag flag='acb12389efgxyz789' position=flag.find_first_not_of (s) cout<<'flag.find_first_not_of (s) :'<<position<<endl //Reverse search, the last position of flag in s flag='3' position=s.rfind (flag) cout<<'s.rfind (flag) :'<<position<<endl }

説明:
1.1。



string sub = ”abc“; string s = ”cdeabcigld“;

s.find(sub)とs.rfind(sub)の2つの関数。 subとsの一部が完全に一致する場合、一致するインデックスが返されます。つまり、sに3つの連続する文字abcが含まれる場合、現在のインデックスが返されます。
二。 見つからない場合は、string :: nposを返します。これは大きな数値であり、その値を知る必要はありません。
前任者のブログを参照してください。
https://www.cnblogs.com/web100/archive/2012/12/02/cpp-string-find-npos.html
誰もが批判して訂正することを歓迎します! ! !