C言語で特定の文字を検索する方法は何ですか?

C言語では、strchr関数を使用して、指定された文字が文字列の中でどこにあるかを見つけることができます。

関数のプロトタイプ:

char *strchr(const char *s, int c);

パラメータ説明:

  1. s: 検索する文字列
  2. c:検索する文字

戻り値:

  1. 指定された文字が見つかった場合、その文字へのポインタを返します。
  2. 指定された文字が見つからない場合は、NULLを返します。

コードの例:

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

int main() {
    char str[] = "Hello, World!";
    char *ptr = strchr(str, 'o');
    
    if (ptr != NULL) {
        printf("找到字符'o'在字符串中的位置:%d\n", ptr - str);
    } else {
        printf("未找到指定字符\n");
    }
    
    return 0;
}

結果を出力します。

找到字符'o'在字符串中的位置:4
bannerAds