各种库函数的模拟实现
一、模拟实现strlen
二、模拟实现strcpy 三、模拟实现strcmp 四、模拟实现strcat 五、模拟实现strstr
一、模拟实现strlen
模拟实现strlen有三种方法
1.地址-地址型
2.递归型
3.计数器型
1.地址-地址型
# include <stdio.h>
int main ( )
{
const char * str = "abcdef" ;
const char * p1 = 0 ;
const char * p2 = 0 ;
p1 = str;
while ( * ( str++ ) != '\0' )
{ }
str-- ;
p2 = str;
printf ( "%d" , p2- p1) ;
return 0 ;
}
2.递归型
# include <stdio.h>
# include <assert.h>
int my_strlen ( const char * str)
{
assert ( str) ;
if ( ( * str) != '\0' )
return my_strlen ( ++ str) + 1 ;
else
return 0 ;
}
int main ( )
{
const char * str = "abcdef" ;
int ret = my_strlen ( str) ;
printf ( "%d" , ret) ;
return 0 ;
}
3.计数器型
# include <stdio.h>
# include <assert.h>
int my_strlen ( const char * str)
{
assert ( str) ;
int i = 0 ;
while ( * ( str++ ) != '\0' )
{
i++ ;
}
return i;
}
int main ( )
{
const char * str = "abcdef" ;
int ret = my_strlen ( str) ;
printf ( "%d" , ret) ;
return 0 ;
}
二、模拟实现strcpy
# include <stdio.h>
# include <assert.h>
char * my_strcpy ( char * str2, const char * str1)
{
assert ( str2 && str1) ;
char * ret = str2;
while ( * str2++ = * str1++ )
{
;
}
return ret;
}
int main ( )
{
char str1[ ] = "abcdef" ;
char str2[ 20 ] = { 0 } ;
printf ( "%s\n" , str1) ;
printf ( "%s\n" , my_strcpy ( str2, str1) ) ;
return 0 ;
}
三、模拟实现strcmp
# include <stdio.h>
# include <string.h>
# include <assert.h>
int my_strcmp ( const char * str1 , const char * str2)
{
assert ( str1 && str2) ;
while ( * str1 >= * str2)
{
if ( * str2 == '\0' )
return 0 ;
str1++ ;
str2++ ;
}
return str1 - str2;
}
int main ( )
{
char str1[ ] = "abcdef" ;
char str2[ ] = "abcd" ;
if ( my_strcmp ( str1, str2) > 0 )
{
printf ( ">\n" ) ;
}
else if ( my_strcmp ( str1, str2) == 0 )
{
printf ( "=\n" ) ;
}
else if ( my_strcmp ( str1, str2) < 0 )
{
printf ( "<\n" ) ;
}
else
{
printf ( "error\n" ) ;
}
return 0 ;
}
四、模拟实现strcat
# include <stdio.h>
# include <string.h>
# include <assert.h>
char * my_strcat ( char * str1, const char * str2)
{
char * p1 = str1;
const char * p2 = str2;
while ( * ( p1) != '\0' )
{
p1++ ;
}
while ( * ( p2) != '\0' )
{
* ( p1++ ) = * p2;
p2++ ;
}
* p1 = '\0' ;
return str1;
}
int main ( )
{
char str1 [ 10 ] = "aaa" ;
char str2 [ 10 ] = "bbb" ;
printf ( "%s" , my_strcat ( str1, str2) ) ;
return 0 ;
}
五、模拟实现strstr
# include <stdio.h>
# include <string.h>
# include <assert.h>
const char * my_strstr ( const char * str1, const char * str2)
{
assert ( str1 && str2) ;
const char * p1 = str1;
const char * p2 = str2;
const char * cp = str1;
while ( * ( p1) != * ( p2) )
{
if ( p1 && p2 == 0 )
return 0 ;
p1++ ;
}
cp = p1;
while ( * p1 == * p2)
{
if ( * p2 == '\0' )
return cp;
if ( * p1 == '\0' )
return 0 ;
p1++ ;
p2++ ;
}
return 0 ;
}
int main ( )
{
char str1[ ] = "abcdef" ;
char str2[ ] = "def" ;
printf ( "%p" , my_strstr ( str1, str2) ) ;
return 0 ;
}