在C語言中,如果要查找一個(gè)指定的字符串,可以使用庫函數(shù)strstr()
。該函數(shù)用于在一個(gè)字符串中查找另一個(gè)指定的字符串,并返回第一次出現(xiàn)的位置。
函數(shù)原型如下:
char *strstr(const char *haystack, const char *needle);
參數(shù)說明:
haystack
:要查找的字符串。needle
:要查找的目標(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
,并返回str2
在str1
中第一次出現(xiàn)的位置。在本例中,str2
在str1
中第一次出現(xiàn)的位置是索引10。