C言語 strstr関数:文字列検索の基本と実践
strstr関数は、1つの文字列内で別の文字列が最初に現れる位置を検索するために使用されます。関数のプロトタイプは以下の通りです:
char *strstr(const char *haystack, const char *needle);
haystackは検索する文字列を表し、needleは検索対象の部分文字列を表します。
使い方は以下の通りです:
#include <stdio.h>
#include <string.h>
int main() {
const char *haystack = "Hello, world!";
const char *needle = "world";
char *result = strstr(haystack, needle);
if (result) {
printf("'%s' found at position %ld\n", needle, result - haystack);
} else {
printf("'%s' not found\n", needle);
}
return 0;
}
haystack中のneedleを検索して、見つかった場合はその位置を出力し、見つからない場合はメッセージを出力します。