strstr
()函數:
strstr
(str1,str2)函數用於判斷字符串str2是否是str1的子串。如果是,則返回str2在str1中首次出現的地址:否則,返回NULL。
在庫函數中
strstr
()函數的原型是
char
*
strstr
(
const
char
* str1,
const
char
* str2 ),包含在頭文件<string.h>中。
思路:1.判空及判斷str1與str2的長度比較;
2. 從字符串str1和str2開始遍歷,直到str2結束,即遇見str2的
'\0'
,尋找成功,返回str1與str2第一個字符相等的首地址,否則,返回NULL;
3.在第二種情況下,在相同幾步之後有可能有不相等的情況,如:“12234”與“234”,則將開始的str1++,重複第2步;
4..在這裏寫代碼時需注意的幾點:
const
(保證了數據的安全性);
char
*(爲了實現鏈式訪問);重複時的處理即第三種情況。相信,細節乃畫龍點睛之筆喔!
5.代碼:
(1)在庫中的代碼如下:
char
*
strstr
(
const
char
* str1,
const
char
* str2 )
{
char
*cp = (
char
*) str1;
char
*s1, *s2;
if
( !*str2 )
return
((
char
*)str1);
while
(*cp)
{
s1 = cp;
s2 = (
char
*) str2;
while
( *s1 && *s2 && !(*s1-*s2) )
/*在c語言中指針與指針相減,得到的是元素的個數*/
s1++, s2++;
if
(!*s2)
return
(cp);
cp++;
}
return
(NULL);
}
(2)我的代碼:
# include <stdio.h>
char
* my_strstr(
const
char
*s1,
const
char
*s2)
{
int
n=0;
//在開始比較字符相等時走的步數
if
(*s2)
{
while
(*s1)
{
if
(*(s1 + n) == *(s2 + n))
{
if
(*(s2 + n + 1) == NULL)
{
return
(
char
*)s1;
}
n++;
}
/* for (n=0; *(s1 + n) == *(s2 + n); n++)
{
if (*(s2 + n + 1)==NULL)
return (char *)s1;
} */
s1++;
//只要第n次不相等時,就進行s1++,直到滿足條件時開始返回執行循環語句
}
return
NULL;
}
else
return
NULL;