在C語(yǔ)言中,可以使用字符串處理函數(shù)strstr來(lái)查找子串。該函數(shù)的原型為:
char *strstr(const char *haystack, const char *needle);
其中,haystack表示要在其中查找子串的字符串,needle表示要查找的子串。函數(shù)返回一個(gè)指向第一次出現(xiàn)子串的位置的指針,如果未找到則返回NULL。
以下是一個(gè)示例代碼,演示如何在C中使用strstr函數(shù)查找子串:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char subStr[] = "World";
char *result = strstr(str, subStr);
if (result) {
printf("子串 \"%s\" 在字符串 \"%s\" 中的位置是:%ld\n", subStr, str, result - str);
} else {
printf("未找到子串 \"%s\" 在字符串 \"%s\" 中\(zhòng)n", subStr, str);
}
return 0;
}
運(yùn)行結(jié)果將輸出:
子串 "World" 在字符串 "Hello, World!" 中的位置是:7