模拟实现的字符串处理函数:
strlen,strcat,strncat,strchr,strrchr,strcpy,strncpy
1.strlen,求字符串的长度,不算‘/0’
复制代码
1
2
3
4
5
6
7
size_t mystrlen(const char *string)
{
const char *p = string;
while (*p++)
{}
return(p - string - 1);
}
2.strcat,拼接字符串
复制代码
1
2
3
4
5
6
7
8
9
10
char *mystrcat(char *dest, const char *source)//两个字符串拼接
{
char *address = dest;
assert((*dest != NULL) && (*source != NULL));
while (*dest++)
{}
while (*(dest++) = *(source++))
{}
return address;
}
3.strncat,拼接字符串,把第二串字符串前count字符拼接到第一个字符串后面
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char *mystrncat(char *dest, const char* source,size_t count)//把2字符串前count个接到1字符串后面
{
char *address = dest;
assert((*dest != NULL) && (*source != NULL));
while (*dest != '')
{
dest++;
}
while (count && (*dest++ = *source++))
{
count--;
}
*dest = '';
return address;
}
4.strchr,找出第一次出现字符C的位置
复制代码
1
2
3
4
5
6
7
8
9
10
11
const char * mystrchr(const char * string,char C)//第一次出现字符的位置,如果没有返回NULL
{
assert(*string != NULL);
while (*string)
{
if (*string == C)
return string;
string++;
}
return NULL;
}
5.strrchr,返回字符C最后出现在字符串的位置
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
const char * mystrrchr(const char * string, char C) //最后一个字符出现的位置,如果没有返回NULL
{
const char* tmp = NULL;
assert(*string != NULL);
while (*string)
{
if (*string == C)
tmp = string;
string++;
}
return tmp;
}
6.strcpy,字符串拷贝
复制代码
1
2
3
4
5
6
7
8
char * mystrcpy(char *dest, const char *source)
{
char *address = dest;
assert((dest != NULL)&&(source != NULL));
while (*dest++ = *source)
{}
return address;
}
7.strncpy,字符串拷贝,拷贝源字符串count个字符到目的字符串
复制代码
1
2
3
4
5
6
7
8
9
10
11
char *mystrncpy(char *dest, const char *source, size_t count)
{
assert((dest != NULL) && (source != NULL));
char *address = dest;
while (count--)
{
*dest++ = *source++;
}
*dest = '';
return address;
}
最后
以上就是年轻可乐最近收集整理的关于模拟实现:strlen,strcat,strchr,strcpy,strcat...的全部内容,更多相关模拟实现:strlen,strcat,strchr,strcpy,strcat内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复