C语言 strstr 函数:查找字符串的利器
strstr 函数是 C 语言中的一个字符串处理函数,用于在一个字符串中查找另一个字符串第一次出现的位置。它的原型如下:
char *strstr(const char *haystack, const char *needle);
该函数将在 haystack 字符串中查找 needle 字符串第一次出现的位置,并返回一个指向该位置的指针。如果找到了 needle,则返回第一次出现的位置的指针;如果未找到,则返回 NULL。
该函数可以用于在字符串中查找子字符串,例如:
const char *str = 'Hello, World!';
const char *subStr = 'World';
char *result = strstr(str, subStr);
if (result != NULL) {
printf('Found at position: %ld\n', result - str);
} else {
printf('Not found\n');
}
上述代码会输出 'Found at position: 7',表示在 str 字符串中找到了'World' 子字符串,它的起始位置是在第 7 个字符处。
原文地址: https://www.cveoy.top/t/topic/qtBP 著作权归作者所有。请勿转载和采集!