温馨提示×

c语言中strchr()和strstr()函数怎么使用

小亿
93
2023-11-10 11:57:31
栏目: 编程语言

在C语言中字符串处理函数`strchr()`或`strstr()`用于在字符串中查找特定字符或子字符串的位置。

以下是这两个函数的基本用法:

1、strchr()

#include 
char *strchr(const char *str, int c);

该函数在给定的字符串`str`中查找第一个出现的字符`c`,并返回其指针。如果未找到,则返回`NULL`。

例如:

#include 
#include 
int main() {
    const char *str = "Hello, world!";
    char *position = strchr(str, 'o');
    
    if (position != NULL) {
        printf("Found at position: %ld\n", position - str);
    } else {
        printf("Not found!\n");
    }
    
    return 0;
}

2、strstr()

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

该函数在给定的字符串`haystack`中查找第一次出现的子字符串`needle`,并返回其指针。如果未找到,则返回`NULL`。

例如:

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

请注意,这些函数在找到匹配项时返回指向字符串中的位置的指针,并且返回的位置是相对于原始字符串起始位置的偏移量。

0