strstr
- 函数标准格式
char *strstr( const char *string, const char *strCharSet );
- 函数功能
- Find a substring. 翻译为 寻找子串。子串就是一个字符串中的一部分。如字符串abcdefg,那么abc是它的子串,cde也是它的子串。只要是和字符串的一部分相同就算是子串。
- 返回值是子串在字符串中首次出现的位置(地址)
- 子串是空串时,返回的是主字符串
- 在主字符串中没有发现子串时,返回NULL
- 函数实现
char *my_strstr(const char *str1, const char *str2)
{
assert(str1 && str2);
const char *str = (const char*)str1;
const char *substr = (const char*)str2;
char *pstr = NULL;
if (*substr == '\0')
return str1;
while (*str)
{
pstr = str;
substr = str2;
while (*pstr && *substr && (*pstr == *substr))
{
pstr++;
substr++;
}
if (*substr == '\0')
return str;
str++;
}
}
- 例子
char *my_strstr(const char *str1, const char *str2)
{
assert(str1 && str2);
const char *str = (const char*)str1;
const char *substr = (const char*)str2;
char *pstr = NULL;
if (*substr == '\0')
return str1;
while (*str)
{
pstr = str;
substr = str2;
while (*pstr && *substr && (*pstr == *substr))
{
pstr++;
substr++;
}
if (*substr == '\0')
return str;
str++;
}
}
int main()
{
char str[] = "This is a simple string";
char *pch;
pch = my_strstr(str, "simple");
strncpy(pch, "sample", 6);
puts(str);
return 0;
}
- 程序结果
- 可以看到 strstr 函数在字符串中找到了子串simple的位置,并把子串第一次出现的地址返回。strncpy 函数把sample复制进主字符串,地址为子串的地址,由于sample和simple的字符个数相同,所以完全替换simple。