reference to:
http://blog.csdn.net/wangyangkobe/article/details/6787516
http://baike.baidu.com/view/745156.htm
在计算机内存中,0,'\0',null,是一样的,值也是一样的,都是0。以数字的方式读取就是0,以字符串的方式读取就是'\0',以程序命令或者其他方式读取就是null(null的定义跟编译器有关,有的编译器定义null可能不是0)。
请用标准C语言实现下列标准库函数,设计中不得使用其他库函数。
char *strstr(char *str1,char *str2);
在字符串str1中,寻找字串str2,若找到返回找到的位置,否则返回NULL。
- #include <iostream>
- #include <cassert>
- using namespace std;
- const char* StrStr(const char *str1, const char *str2)
- {
- assert(NULL != str1 && NULL != str2);
- if('\0' != *str2)
- {
-
while('\0' != *str1) -
{ -
for(int index = 0; *(str1 + index) == *(str2 +index); index++) - {
-
if('\0'
== *(str2 + index + 1)) - {
-
return
str1; - }
- }
-
str1++; -
} - return NULL;
- }
- else
- {
-
return str1; - }
- }
- int main()
- {
-
const char *str1
= "wangyang"; -
const char *str2[]
= {"", "wx", "ang"}; - for(int index = 0; index < 3; index++)
- {
- const char *res = StrStr(str1, str2[index]);
- if(res != NULL)
-
cout<<str2[index]<<":Find, start pointer
is:"<<res<<endl; - else
-
cout<<str2[index]<<":Not Find"<<endl;
- }
- system("pause");
- }