第二个我做不到,既要返回索引,又要返回-1。
size_t 不行,当返回值为 SIZE_MAX 时无法区分是在 SIZE_MAX 找到了子字符串还是没找到返回了 size_t(-1)
ssize_t 更不行
ptrdiff_t 也不行,当 大于PTRDIFF_MAX 小于SIZE_MAX 时,结果未定义。
程序代码:
#include <stdio.h>
int my_strcmp( const char* lhs, const char* rhs )
{
for( ; *lhs!='\0' && *lhs==*rhs; ++lhs,++rhs);
unsigned char a = *(const unsigned char*)lhs;
unsigned char b = *(const unsigned char*)rhs;
return a-b;
}
char* my_strstr( const char* str, const char* substr )
{
if( !*substr )
return (char*)str;
for( ; *str; ++str )
{
const char* p = str;
const char* q = substr;
for( ; *q!=0 && *p==*q; ++p,++q );
if( !*q )
return (char*)str;
}
return NULL;
}
#include <iostream>
using namespace std;
int main( void )
{
cout << my_strcmp("A","B") << endl;
cout << my_strcmp("computer","compare") << endl;
cout << my_strstr("abcd","bc") << endl;
cout << my_strstr("abcd","cd") << endl;
cout << my_strstr("abcd","") << endl;
cout << my_strstr("","") << endl;
const char* s = "The quick brown dog jumps over the lazy fox";
cout << (my_strstr(s,"lazy")-s) << endl;
}