以下是我用C语言模拟实现的部分字符串函数:
1、strncpy函数的实现
#include<stdio.h>
#include<assert.h>
#include<iostream>
char*my_strncpy(char*dest, const char*src, int n)
{
assert(dest != NULL);
assert(src != NULL);
int i = 0;
char *tmp = dest;
while ((i++<n)&&(*tmp++ = *src++ )!= '\0')
{
;
}
return dest;
}
int main()
{
char str1[] = "1234567890";
char str2[] = "abcde";
my_strncpy( str1,str2, 6);
printf("%s\n", str1);
system("pause");
return 0;
}
2、strncmp函数的实现
#include<stdio.h>
#include<iostream>
#include<assert.h>
int my_strncmp(const char*str1, const char*str2,int n)
{
assert(str1 != NULL);
assert(str2 != NULL);
while ((*str1!='\0')&&(*str2!='\0')&&n)
{
if ((*str1 - *str2) > 0)
return 1;
if ((*str1-*str2)<0)
return -1;
str1++;
str2++;
n--;
}
if (*str1 == '\0'&&*str2 != '\0')
return -1;
if (*str1 != '\0'&&*str2 == '\0')
return 1;
return 0;
}
int main()
{
char str1[] = "abcdef";
char str2[] = "abcmln";
int ret = my_strncmp(str1, str2,4);
printf("%d\n", ret);
system("pause");
return 0;
}
3、strncat函数实现
#include<stdio.h>
#include<assert.h>
#include<iostream>
char*my_strncat(const char*src,char*dest, int n)
{
assert(src != NULL&&dest != NULL);
char*tmp = dest;
while (*tmp != '\0')
{
tmp++;
}
while ((n--) && (*tmp++ = *src++) != '\0')
{
;
}
return dest;
}
int main()
{
char str1[20] = "hello ";
char str2[6] = "word!";
my_strncat(str2, str1, 2);
printf("%s\n", str1);
system("pause");
return 0;
}
4、strstr函数的实现
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<iostream>
char*my_strstr(char*str1, char*str2)
{
assert(str1 != NULL&&str2 != NULL);
int i = 0;
int j = 0;
char*ret = 0;
for (i = 0; str1[i] != 0; i++)
{
for (j = 0; str2[j] != 0; j++)
{
if (str1[i + j] != str2[j])
{
break;
}
}
if (str2[j] == 0)
return str1 + i;
}
return NULL;
}
int main()
{
char str[] = "abbcdbcdefmln";
char str1[] = "bcd";
//char *tmp=my_strstr(str, str1);
printf("%s", my_strstr(str, str1));
system("pause");
return 0;
}
5、strrstr函数的实现
#include<stdio.h>
#include<assert.h>
#include<iostream>
char*my_strrstr(char*str1, char*str2)
{
assert(str1 != NULL&&str2 != NULL);
int i = 0;
int j = 0;
char*ret = 0;
for (i = 0; str1[i] != 0; i++)
{
for (j = 0; str2[j] != 0; j++)
{
if (str1[i + j] != str2[j])
{
break;
}
}
if (str2[j] == 0)
ret=str1+i;
}
return ret;
}
int main()
{
char str[] = "abbcdbcdefmln";
char str1[] = "bcd";
//char *tmp=my_strstr(str, str1);
printf("%s", my_strrstr(str, str1));
system("pause");
return 0;
}