strstr c语言字符串,C字符串处理strstr, strindex
有的時候,我們?yōu)榱艘恍┨厥獾男枰?#xff0c;不能使用C語言提供的字符串處理函數(shù),而需要我們自己動手來寫,下面是兩個比較常用的例子:
(1) strstr
原型聲明:char *strstr (const char *s1, char *s2);
改函數(shù)從字符串s2中查找子字符串s1, 如果找到了返回子找到位置的子字符串的指針,否則返回NULL.
(2)strindex
原型聲明:int strindex (const char *s1, char *s2);
返回字符串s2在字符串s1中的位置,這個位置是從0開始的,如果沒有找到,則返回-1
下面是實現(xiàn)以及使用的例子:
/*
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) | 轉發(fā)(1) |
總結
以上是生活随笔為你收集整理的strstr c语言字符串,C字符串处理strstr, strindex的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux检查镜像,Shell脚本实现检
- 下一篇: c语言若对函数未加,【单选题】C 语言程