模拟实现字符串函数(续)

时间:2023-01-04 12:18:30

一、模拟实现strncpy函数,函数原型:char *strncpy(char *dest, char *src, size_t n)。

#include <stdio.h>
#include <iostream>
#include <assert.h>

char* my_strncpy(char *dest,const char *src,size_t count)
{
assert(dest);
while (count--)
{
if (*src!='\0')
{
*dest++ = *src++;
}
}
return dest;
}

int main()
{
char arr[20] = "aaaaaaworld!";
char *p = "hello ";

my_strncpy(arr, p, 6);

printf("%s\n", arr);
system("pause");
return 0;
}

运行结果如图所示:

模拟实现字符串函数(续)

二、模拟实现strncat函数,函数原型:char * strncat(char *dest, const char *src, size_t n)。

#include <stdio.h>
#include <iostream>
#include <assert.h>

char *my_strncat(char *dest,const char *src,size_t count)
{
assert(dest);
assert(src);

while (*dest!='\0')
{
*dest++;
}
while (*src&&count--)
{
*dest++ = *src++;
}
*dest = '\0';
return dest;
}

int main()
{
char arr[20] = "hello ";
char *p = "bit!";
my_strncat(arr, p, 4);
printf("%s\n", arr);
system("pause");
return 0;
}

运行结果如图所示:

模拟实现字符串函数(续)

三、模拟实现strncmp函数,函数原型:int strncmp ( const char * str1, const char * str2, size_t n )。

#include <stdio.h>
#include <iostream>
#include <assert.h>

int my_strncmp(const char *str1,const char *str2,size_t count)
{
assert(str1);
assert(str2);
while ((*str1 == *str2)&&--count)
{
*str1++;
*str2++;
if (*str1 == '\0')
{
return -1;
}
if (*str2 == '\0')
{
return 1;
}
}
return *str1 - *str2;
}
int main()
{
const char *str1 = "abc";
const char *str2 = "ab";
int ret = my_strncmp(str1, str2,5);
if (ret == 0)
{
printf("str1=str2");
}
if (ret < 0)
{
printf("str1<str2");
}
if (ret > 0)
{
printf("str1>str2");
}
system("pause");
return 0;
}


四、模拟实现strstr函数,函数原型:char *strstr(const char *str1, const char *str2)。

#include <stdio.h>
#include <iostream>
#include <assert.h>

char *my_strstr(const char *str1,const char *str2)
{
assert(str1);
assert(str2);
char *s1 = (char*)str1;
char *s2 = (char*)str2;
char *s = (char*)str1;
if (*str2 == '\0')
{
return (char*)str1;
}
while (*s)
{
s1 = s;
s2 =(char*) str2;
while (*s1 == *s2)
{
*s1++;
*s2++;
}
if (*s2 == '\0')
{
return s;
}
if (*s1 == '\0')
{
return NULL;
}
s++;
}
return NULL;
}
int main()
{
const char *str = "Happy birthday to to to you!";
const char *p = "to";
printf("%s\n", my_strstr(str, p));
system("pause");
return 0;
}


运行结果如图所示:

模拟实现字符串函数(续)


五、模拟实现strrstr函数。


#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <string.h>

char *strrstr(const char *str1, const char *str2)
{
assert(str1);
assert(str2);
if (*str2 == '\0')
{
return NULL;
}
int len1 = strlen(str1);
int len2 = strlen(str2);
str1 += len1 - 1;
str2 += len2 - 1;
char *s1 = (char *)str1;
char *s2 = (char *)str2;
char *s = (char *)str1;
while (*s)
{
s1 = s;
s2 = (char*)str2;
while (*s1 == *s2)
{
*(--s1);
*(--s2);
}
if (*s1 == '\0')
{
return NULL;
}
if (*s2 == '\0')
{
return s;
}
--s;
}
return NULL;
}
int main()
{
const char *str = "I love love love you!";
const char *p = "love";
printf("%s\n", strrstr(str, p));
system("pause");
return 0;
}

运行结果如图所示:

模拟实现字符串函数(续)