溫馨提示×

c語言怎么在字符串中查找指定字符串

小億
490
2024-04-12 11:43:55
欄目: 編程語言

在C語言中,可以使用strstr()函數來在一個字符串中查找另一個字符串。該函數的原型為:

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

其中,haystack是要查找的字符串,needle是要查找的子字符串。該函數返回子字符串在字符串中的第一個匹配位置的指針,如果未找到則返回NULL。

下面是一個示例代碼:

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

int main() {
    char str1[] = "Hello, world!";
    char str2[] = "world";

    char *ptr = strstr(str1, str2);

    if (ptr) {
        printf("'%s' found at position %ld\n", str2, ptr - str1);
    } else {
        printf("'%s' not found\n", str2);
    }

    return 0;
}

運行結果為:

'world' found at position 7

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女