溫馨提示×

c語言中strchr()和strstr()函數怎么使用

小億
142
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女