Cライブラリ関数 -strstr()
説明
Cライブラリ関数char *strstr(const char *haystack, const char *needle) 文字列haystackの中から最初に出現する文字列needleの位置を検索し、終端文字は含みません。\0。
strstr() は C 標準ライブラリの文字列処理関数であり、ある文字列の中で部分文字列が最初に出現する位置を検索するために使用されます。
宣言
以下は strstr() 関数の宣言です。
char *strstr(const char *haystack, const char *needle);
strstr() 関数は、文字列 haystack の中で部分文字列 needle が最初に出現する位置を検索するために使用されます。見つかった場合はその位置を指すポインタを返し、見つからない場合は NULL を返します。
パラメータ
- haystack-- 検索するメイン文字列。
- needle-- 検索する部分文字列。
戻り値
haystack 内で needle が最初に出現する位置を指すポインタを返します。needle が haystack 内で見つからない場合は、NULL を返します。
例
以下の例は、strstr() 関数の使用方法を示しています。
例 1
#include <stdio.h>
#include <string.h>
int main()
{
const char haystack[20] = "サンプル";
const char needle[10] = "NOOB";
char *ret;
ret = strstr(haystack, needle);
printf("部分文字列は: %s\n", ret);
return(0);
}
上記のプログラムをコンパイルして実行すると、次の結果が得られます:
子字符串是: NOOB
例 2
#include <stdio.h>
#include <string.h>
int main() {
const char *haystack = "Hello, world! This is a test string.";
const char *needle = "world";
// haystack 内で needle を検索する
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("Substring found: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}
#include <string.h>
int main() {
const char *haystack = "Hello, world! This is a test string.";
const char *needle = "world";
// haystack 内で needle を検索する
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("Substring found: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}
コードの説明:
strstr()関数はhaystackの先頭から検索を開始しneedle、一致する部分文字列が見つかるか、またはhaystackの末尾に達するまで続けます。もし
needleが空文字列の場合(""),strstr()返されるのはhaystackの開始アドレスです。strstr()は大文字と小文字を区別します。大文字と小文字を区別しない検索が必要な場合は、strcasestr()(非標準関数であり、特定のライブラリのサポートが必要な場合があります)。
出力結果:
Substring found: world! This is a test string.その他の拡張
C標準ライブラリ - <string.h>