Namespaces
Variants

strstr

From cppreference.net
< c ‎ | string ‎ | byte
ヘッダーで定義 <string.h>
char * strstr ( const char * str, const char * substr ) ;
(1)
/*QChar*/ * strstr ( /*QChar*/ * str, const char * substr ) ;
(2) (C23以降)
1) substr が指すヌル終端バイト文字列が、 str が指すヌル終端バイト文字列内で最初に現れる位置を検索します。終端のヌル文字は比較対象になりません。
2) (1) に相当する型総称関数。 T を修飾なしの文字オブジェクト型とする。
  • str の型が const T * の場合、戻り値の型は const char * となる。
  • それ以外の場合、 str の型が T * の場合、戻り値の型は char * となる。
  • それ以外の場合、動作は未定義となる。
これらの各総称関数のマクロ定義が抑制されて実際の関数にアクセスする場合(例えば ( strstr ) が使用される場合や関数ポインタが使用される場合)、実際の関数宣言 (1) が可視となる。

str または substr のいずれかが、null終端バイト文字列へのポインタでない場合、動作は未定義です。

目次

パラメータ

str - 検査対象のnull終端バイト文字列へのポインタ
substr - 検索対象のnull終端バイト文字列へのポインタ

戻り値

見つかった部分文字列の最初の文字へのポインタを str で返す。該当する部分文字列が見つからない場合はヌルポインタを返す。 substr が空文字列を指している場合は、 str が返される。

#include <stdio.h>
#include <string.h>
void find_str(char const* str, char const* substr)
{
    char const* pos = strstr(str, substr);
    if (pos)
        printf(
            "Found the string [%s] in [%s] at position %td\n",
            substr, str, pos - str
        );
    else
        printf(
            "The string [%s] was not found in [%s]\n",
            substr, str
        );
}
int main(void)
{
    char const* str = "one two three";
    find_str(str, "two");
    find_str(str, "");
    find_str(str, "nine");
    find_str(str, "n");
    return 0;
}

出力:

Found the string [two] in [one two three] at position 4
Found the string [] in [one two three] at position 0
The string [nine] was not found in [one two three]
Found the string [n] in [one two three] at position 1

参考文献

  • C23規格 (ISO/IEC 9899:2024):
  • 7.24.5.7 strstr関数 (p: TBD)
  • C17規格 (ISO/IEC 9899:2018):
  • 7.24.5.7 strstr関数 (p: 269)
  • C11標準 (ISO/IEC 9899:2011):
  • 7.24.5.7 strstr関数 (p: 369)
  • C99規格 (ISO/IEC 9899:1999):
  • 7.21.5.7 strstr関数 (p: 332)
  • C89/C90標準 (ISO/IEC 9899:1990):
  • 4.11.5.7 strstr関数

関連項目

文字の最初の出現位置を検索
(関数)
文字の最後の出現位置を検索
(関数)