strstr関数 - 文字列が含まれているかをチェックする
文字列が含まれているかをチェックするにはstrstr関数を使用します。string.hを読み込むと、strstr関数を使用できます。
#include <string.h> char * strstr(const char *str1, const char *str2);
str1の中にstr2が含まれている場合は、マッチした最初のアドレスを返します。見つからなかった場合は、NULLを返します。
C言語では文字列は「\0」で終わるという約束事があります。strstr関数は、この約束事を前提として、文字列の検索を行います。
strstr関数を使う場合は、引数の二つの文字列が「\0」で終わっていることを必ず確認してください。
文字列が含まれているかどうかをチェックする
strstr関数で、文字列が含まれているかをチェックするサンプルです。NULLでないことを確認すればOKです。
#include <string.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
const char* message = "I like orange\n";
const char* match = "orange";
if (strstr(message, match) != NULL) {
printf("Match\n");
}
else {
printf("Not Match\n");
}
}
出力結果です。
Match
文字列が含まれている個数を数える
strstr関数は、マッチした場合に、その位置を返すので、このことを利用して、文字列が含まれている個数を数えてみましょう。
#include <string.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
const char* message = "I like orangeorange and orange.\n";
const char* match = "orange";
int32_t match_length = strlen(match);
int32_t match_count = 0;
const char* message_ptr = message;
while (1) {
message_ptr = strstr(message_ptr, match);
if (message_ptr != NULL) {
match_count++;
message_ptr += match_length;
}
else {
break;
}
}
printf("Match Count %d\n", match_count);
}
出力結果です。
Match Count 3
C言語ゼミ


