溫馨提示×

C語言函數strstr如何使用

小億
146
2023-09-29 00:38:39
欄目: 編程語言

函數strstr用于在一個字符串中搜索另一個字符串的出現位置。它的聲明如下:

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

其中,haystack表示要搜索的字符串,needle表示要搜索的子字符串。

使用方法如下:

#include <stdio.h>
#include <string.h>
int main()
{
const char *haystack = "Hello, World!";
const char *needle = "World";
char *result = strstr(haystack, needle);
if(result != NULL)
{
printf("'%s' is found in '%s' at position %ld\n", needle, haystack, result - haystack);
}
else
{
printf("'%s' is not found in '%s'\n", needle, haystack);
}
return 0;
}

輸出結果為:

'World' is found in 'Hello, World!' at position 7

上述代碼中,首先定義了一個haystack字符串和一個needle字符串。然后使用strstr函數在haystack字符串中搜索needle字符串的出現位置。如果找到了,則返回指向該位置的指針;如果未找到,則返回NULL。最后根據返回的結果進行相應的輸出。

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