logo

C++ での文字列検索

find は、呼び出される指定された文字列内で最初に出現する部分文字列を検索するために使用されます。指定された開始位置から文字列内で最初に出現する部分文字列のインデックスを返します。開始位置のデフォルト値は 0 です。

のメンバー関数です std::文字列 クラス。



構文:

size_t find (const string& str, size_t pos = 0); // for C++ Style Strings or size_t find (const char* s, size_t pos = 0); // for C-Style Strings>

パラメーター:

    str : 検索する部分文字列。 s : 検索対象の部分文字列。C スタイルの文字列として指定されます。 pos : 文字列検索を開始する最初の位置。

戻り値:



  • この関数は、最初に出現した部分文字列のインデックスを返します。
  • サブ文字列が見つからない場合は、string::npos (string::pos は、size_t データ型で可能な最大の値を持つ静的メンバーです) を返します。

複雑さの分析:

    時間計算量: O(N*M)、 ここで、N は文字列 (str) のサイズ、M は検索される部分文字列のサイズです。補助スペース: O(1)

例:

C++



Pythonの剰余演算子




// C++ program to demonstrate> // working of string.find()> #include> #include> using> namespace> std;> // Driver code> int> main()> {> >string str =>'geeksforgeeks a computer science'>;> >string str1 =>'geeks'>;> > >// Find first occurrence of 'geeks'> >size_t> found = str.find(str1);> >if> (found != string::npos)> >cout <<>'First occurrence is '> <<> >found << endl;> > >// Find next occurrence of 'geeks'.> >// Note here we pass> >// 'geeks' as C style string.> >char> arr[] =>'geeks'>;> >found = str.find(arr, found+1);> >if> (found != string::npos)> >cout <<>'Next occurrence is '> <<> >found << endl;> >return> 0;> }>

>

>

100のうち25は何ですか
出力

First occurrence is 0 Next occurrence is 8>

文字の出現を見つける

find 関数を使用すると、文字列内の 1 つの文字の出現も検索できます。

構文:

size_t find (const char c, size_t pos = 0);>

ここ、 c 検索する文字です。

例:

C++




// C++ program to demonstrate> // working of string find> // to find occurrence of> // a character> #include> #include> using> namespace> std;> // Driver code> int> main()> {> >string str =>'geeksforgeeks a computer science'>;> >char> c =>'g'>;> >// Find first occurrence of 'g'> >size_t> found = str.find(c);> >if> (found != string::npos)> >cout <<>'First occurrence is '> <<> >found << endl;> > >// Find next occurrence of 'g'> >found = str.find(c, found + 1);> >if> (found != string::npos)> >cout <<>'Next occurrence is '> <<> >found << endl;> >return> 0;> }>

>

>

出力

First occurrence is 0 Next occurrence is 8>

文字列の一部を検索する

指定された文字列の一部を検索することもできます。

機械学習の種類

構文:

size_t find (const char *str, size_t pos, size_t n);>

ここ、 n は一致する文字数です。

例:

C++




// C++ program to demonstrate> // working of string find to> // search a string> #include> #include> using> namespace> std;> // Driver code> int> main()> {> >string str =>'geeksforgeeks a computer science'>;> > >// Only search first 5 characters> >// of 'geeks.practice'> >size_t> found = str.find(>'geeks.practice'>,> >0, 5);> >if> (found != string::npos)> >cout << found << endl;> >return> 0;> }>

>

>

出力

0>