溫馨提示×

c語言查找指定字符串的方法是什么

小億
199
2023-11-28 14:43:49
欄目: 編程語言

在C語言中,如果要查找一個(gè)指定的字符串,可以使用庫函數(shù)strstr()。該函數(shù)用于在一個(gè)字符串中查找另一個(gè)指定的字符串,并返回第一次出現(xiàn)的位置。

函數(shù)原型如下:

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

參數(shù)說明:

  • haystack:要查找的字符串。
  • needle:要查找的目標(biāo)字符串。

返回值:

  • 如果找到目標(biāo)字符串,返回目標(biāo)字符串在原字符串中的位置。
  • 如果沒有找到目標(biāo)字符串,返回NULL。

使用示例:

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

int main() {
    char str1[50] = "This is a test string";
    char str2[10] = "test";
    char *ptr;

    // 在str1中查找str2
    ptr = strstr(str1, str2);

    if (ptr != NULL) {
        printf("目標(biāo)字符串在位置:%ld\n", ptr - str1);
    } else {
        printf("未找到目標(biāo)字符串\n");
    }

    return 0;
}

輸出:

目標(biāo)字符串在位置:10

上述示例中,strstr(str1, str2)會(huì)在str1中查找str2,并返回str2str1中第一次出現(xiàn)的位置。在本例中,str2str1中第一次出現(xiàn)的位置是索引10。

0