日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

strstr c语言字符串,C字符串处理strstr, strindex

發布時間:2025/3/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 strstr c语言字符串,C字符串处理strstr, strindex 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

有的時候,我們為了一些特殊的需要,不能使用C語言提供的字符串處理函數,而需要我們自己動手來寫,下面是兩個比較常用的例子:

(1) strstr

原型聲明:char *strstr (const char *s1, char *s2);

改函數從字符串s2中查找子字符串s1, 如果找到了返回子找到位置的子字符串的指針,否則返回NULL.

(2)strindex

原型聲明:int strindex (const char *s1, char *s2);

返回字符串s2在字符串s1中的位置,這個位置是從0開始的,如果沒有找到,則返回-1

下面是實現以及使用的例子:

/*

File Name: str.c

Function: to find a sub string in a string.

*/

#includechar *strstr (const char *s1, const char *s2);

int strindex (const char *s1, const char *s2);

int main()

{

char *s1 = "Hello, Welcome to linux world.";

char *s2 = "linux";

char *res = NULL;

printf("string: %s\n", s1);

printf("sub string: %s\n", s2);

printf("now we will find sub string \"%s\" in \"%s\"\n", s2, s1);

if ( (res = strstr(s1, s2)) == NULL )

{

printf("Can't find the string %s in %s\n", s2, s1);

}

else

{

printf("Find string: %s\n", res);

printf("The position [zero-based] is %d\n", strindex(s1, s2));

}

return 0;

}

char *strstr (const char *s1, const char *s2)

{

unsigned int i = 0;

if ( *s1 == 0 ) // 如果字符串s1為空

{

if ( *s2 ) // 如果字符串s2不為空

return (char*)NULL; // 則返回NULL

return (char*)s1; // 如果s2也為空,則返回s1

}

while ( *s1 ) // 串s1沒有結束

{

i = 0;

while ( 1 )

{

if ( s2[i] == 0 )

{

return (char*)s1;

}

if ( s2[i] != s1[i] )

break;

i++;

}

s1++;

}

return (char*)NULL;

}

int strindex(const char *s1, const char *s2)

{

int nPos = -1;

char *res = strstr(s1, s2);

if ( res )

nPos = res - s1 ;

return nPos;

}

閱讀(3429) | 評論(0) | 轉發(1) |

總結

以上是生活随笔為你收集整理的strstr c语言字符串,C字符串处理strstr, strindex的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。