C言語で文字列を検索する方法は?

C言語では、文字列を検索するためにライブラリ関数strstrを使用できます。strstr関数のプロトタイプは以下のとおりです:

char *strstr(const char *haystack, const char *needle);

haystackは検索する文字列であり、needleは探す文字列を表しています。strstr関数はhaystack内でneedleが最初に現れる位置を探し、その位置を指すポインタを返します。needleが見つからない場合は、NULLが返されます。

以下はサンプルコードです。

#include<stdio.h>
#include<string.h>

int main() {
    const char *haystack = "Hello, world!";
    const char *needle = "world";
    char *result = strstr(haystack, needle);
    
    if (result != NULL) {
        printf("Found at position: %ld\n", result - haystack);
    } else {
        printf("Not found\n");
    }
    
    return 0;
}

結果は次の通りです:

Found at position: 7

“Hello, world!”という文字列において、”world”という部分文字列が7番目の位置に現れることを意味します。

bannerAds