C strchr: Search Characters in Strings

In C language, the strchr function can be used to locate the position of a specified character in a string.

Function prototype:

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

Explanation of parameters:

  1. s: the string to be searched
  2. c: the character to be found

Return value:

  1. If the specified character is found, return a pointer pointing to that character.
  2. Return NULL if the specified character is not found.

Example code:

#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;
}

Output result:

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