C/C++ では、std::strstr() は文字列のマッチングに使用される事前定義関数です。 文字列関数に必要なヘッダー ファイルです。この関数は 2 つの文字列を受け取ります s1 そして s2 引数として指定し、最初に出現する文字列を検索します。 s2 文字列の中で s1 。照合のプロセスには終端の null 文字 (' ') は含まれませんが、機能はそこで停止します。
構文
char * strstr (const char * s1 , const char * s2 );>
パラメーター
- s1 : これは検査される主な文字列です。 s2 : これは、文字列内で検索される部分文字列です。
戻り値
- この関数は、見つかった文字の最初の文字へのポインタを返します。 s2 で s1 それ以外の場合はヌルポインタ s2 には存在しません s1 。
- s2 が空の文字列を指している場合は、s1 が返されます。
例
以下のプログラムは、strstr() 関数の使用法を示しています。
C
// C program to illustrate strstr()> #include> #include> int> main()> {> >// Take any two strings> >char> s1[] =>'techcodeview.com'>;> >char> s2[] =>'for'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >printf>(>'String found
'>);> >printf>(>'First occurrence of string '%s' in '%s' is '> >''%s''>,> >s2, s1, p);> >}> >else> >printf>(>'String not found
'>);> >return> 0;> }> |
>
>
C++
// CPP program to illustrate strstr()> #include> #include> using> namespace> std;> int> main()> {> >// Take any two strings> >char> s1[] =>'techcodeview.com'>;> >char> s2[] =>'for'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >cout <<>'String found'> << endl;> >cout <<>'First occurrence of string ''> << s2> ><<>'' in ''> << s1 <<>'' is ''> << p <<>'''> ><< endl;> >}> >else> {> >cout <<>'String not found'> << endl;> >}> >return> 0;> }> |
>
>出力
String found First occurrence of string 'for' in 'techcodeview.com' is 'forGeeks'>
時間計算量: O(n + m)。n は s1 のサイズ、m は s2 のサイズです。
補助スペース: O(m)、ここで m は s2 のサイズです。
注記: strstr() の公式実装は未指定ですが、その実装は標準の文字列一致アルゴリズムのいずれかで構成されていると想定されます。ここでは、上で述べたように時間と空間の複雑性を持つ Knuth-Morris-Pratt アルゴリズムを使用して実装されると仮定しています。
応用 : 文字列を別の文字列に置き換えます
この例では、strstr() 関数を使用して、最初に部分文字列の出現を検索します。 STL で s1 その後、その単語を次のように置き換えます 文字列 。
C++
// CPP program to illustrate strstr()> #include> #include> using> namespace> std;> int> main()> {> >// Take any two strings> >char> s1[] =>'Fun with STL'>;> >char> s2[] =>'STL'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >strcpy>(p,>'Strings'>);> >cout << s1;> >}> >else> {> >cout <<>'String not found'> << endl;> >}> >return> 0;> }> |
>
>
C
// C program to illustrate strstr()> #include> #include> int> main()> {> >// Take any two strings> >char> s1[] =>'Fun with STL'>;> >char> s2[] =>'STL'>;> >char>* p;> >// Find first occurrence of s2 in s1> >p =>strstr>(s1, s2);> >// Prints the result> >if> (p) {> >strcpy>(p,>'Strings'>);> >printf>(>'%s'>, s1);> >}> >else> >printf>(>'String not found
'>);> >return> 0;> }> |
>
HTMLからjs関数を呼び出す
>出力
Fun with Strings>
時間計算量: O(n + m)。n は s1 のサイズ、m は s2 のサイズです。
補助スペース: O(m)、ここで m は s2 のサイズです。