#include<iostream>
#include<assert.h>
using namespace std;
char* my_strcpy(char* d, char* s)
{
assert(d!=NULL&&s!=NULL);
while (*s != '\0')
{
*d++ = *s++;
}
*d = '\0'; //注意要有此句
return d;
}
char* my_strncpy(char* d, const char* s,int n)
{
assert(d != NULL && s != NULL);
int count = strlen(s);
for (int i = 0; i < n; i++)
{
if (i < count)
{
*d++ = *s++;
}
else
{
*d++ = '\0';
}
}
return d;
}
char* my_strcat(char* p,const char* q)
{
assert(p != NULL && q != NULL);
char* s = p;
while (*s != '\0')
{
s++;
}
while (*q != '\0')
{
*s++ = *q++;
}
*s = '\0';
return p;
}
char* my_strncat(char* p, const char* q,int n)
{
assert(q != NULL && q != NULL);
char* s = p;
while (*s != '\0')
{
s++;
}
int count = strlen(q);
for (int i = 0; i < n; i++)
{
if (i < count)
{
*s++ = *q++;
}
else
{
*s++ = '\0';
}
}
return p;
}
int my_strcmp(char* p, const char* q)
{
int t;
int res=0;
assert(p != NULL && q != NULL);
while (*p != '\0' || *q != '\0')
{
t = *p - *q;
if (t!=0)
{
break;
}
*p++;
*q++;
}
if (t > 0)
{
res = 1;
}
else if (t < 0)
{
res = -1;
}
return res;
}
void my_memcpy(void* d, const void* s,int count)
{
assert(d != NULL && s != NULL);
char* p = (char*)d;
char* q = (char*)s;
while (count--)
{
*p++ = *q++;
}
}
int my_strstr(const char* p,const char* q)
{
int count_d = strlen(p);
int count_s = strlen(q);
int i = 0, j = 0;
while (i < count_d - count_s && j < count_s)
{
if (p[i] == q[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
return i - j;
}
int main()
{
//strcpy模拟实现
//char s[5] = "abcd";
//char t[4] = "efg";
//my_strcpy(s, t);
//cout << s << endl; //输出efg
//strncpy模拟实现
//char str[20] = "abcd";
//const char* str1 = "efg";
//my_strncpy(str, str1,3);
//cout << str << endl; //输出efcd
//strcat模拟实现
// char s[10] = "abcd";//注意长度要给够
//const char* d = "fg";
//my_strcat(s, d);
//cout << s << endl;//输出abcdfg
//strncat模拟实现
//char s[10] = "abcd";//注意长度要给够
//const char* d = "fg";
//my_strncat(s, d,3);
//cout << s << endl;//输出abcdfg
//strcmp模拟实现
//char s[10] = "bbcd";
//const char* d = "abcd";
//int t=my_strcmp(s, d);
//cout << t << endl;//输出1
//memcpy模拟实现
//int s[10] = { 0 };
//const int d[10] = { 1,2,3,4,5,6,7,8,9,10 };
//my_memcpy(s, d,sizeof(int)*10);
//for (int i = 0; i < 10; i++)
//{
// cout << s[i] << " "; //输出1 2 3 4 5 6 7 8 9 10
//}
//cout << endl;
//memcpy应用-----int
//int a[5] = { 1,2,3,4,5 };
//int b[5] = { 0 };
//memcpy(b, a, sizeof(int) * 5);
//for (int i = 0; i < 5; i++)
//{
// cout << b[i] << " ";//输出1 2 3 4 5
//}
memcpy应用-----char
//char s[5] = "abcd";
//char t[5];
//memcpy(t, s, sizeof(char) * 5);
//cout << t << endl;//输出abcd
//const char* s = "Golden Global View";
//char d[20] = {0};
//memcpy(d, s, strlen(s));
//printf("%s", d);//输出Golden Global View
//子串 模式匹配
const char* str1 = "abcabcababacccabc";
const char* str2 = "ababa";
int index = my_strstr(str1, str2);
printf("index = %d\n", index);
return 0;
}
strcpy、strncpy、strcat、strncat、strcmp、memcpy、ststr模拟实现
于 2023-09-27 21:53:02 首次发布