C ++での文字列のfindメソッドとstring :: nposについて話します



Talk About Find Method



find()関数

find()関数は、文字列内の特定の部分文字列を検索するために使用されます。
見つかった場合は、部分文字列の最初の出現の最初の文字の添え字を返します。
見つからない場合は、-1を返します。

簡単な例:



#include #include using namespace std int main(int argc, char** argv) { string s='aabbcc' int index1=s.find('ddd') int index2=s.find('bb') cout<<index1<<endl //Does not contain substring, output -1 cout<<index2<<endl //Include substring, output 2 return 0 }

string :: npos

nposは、存在しない位置を示すために使用される定数であり、値は通常-1です。
ただし、その型はintではなく、string :: size_typeです。

2つを接続します

例えば:



#include #include using namespace std int main(int argc, char** argv) { string s='aabbcc' string::size_type idx idx=s.find('ddd') //Not found, return -1 if(idx==string::npos){ //string::npos is also -1 cout<<'The string was not found!'<<endl } return 0 }

次のように使用することもできます。これはより便利です。

s.find(str)==string::npos If it returnstrue, Indicating that the substring is not found, otherwise it is found.