C言語のstrstr関数の使い方
strstr関数は、ある文字列の別の文字列の出現位置を検索します。宣言は次の通りです。
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 != NULL)
{
printf("'%s' is found in '%s' at position %ld\n", needle, haystack, result - haystack);
}
else
{
printf("'%s' is not found in '%s'\n", needle, haystack);
}
return 0;
}
出力を日本のネイティブに表現する必要がありますが、1つのオプションのみが必要ですか?
'World' is found in 'Hello, World!' at position 7
上記のコードでは、まずhaystack文字列とneedles文字列を定義します。次に、strstr関数を用いてhaystack文字列内でneedles文字列の出現位置を検索します。見つかれば、その位置を示すポインタが返され、見つからなければNULLが返されます。最後に、返された結果に基づいて適切な出力が行われます。