注:以下文档代码中注释段表明为数组写法,未标明为指针写法
目录
1.字符串strlen函数
(1)strlen函数
返回字符串的长度(不包括结尾的0)
(2)strlen的使用
a.代码
int main()
{
char str1[]="abcdef";
printf("%d\n",strlen(str1));
return 0;
}
b.结果

(3)模拟实现strlen函数
a.代码
#include<stdio.h>
#include<string.h>
int Mystrlen(char *a)
{
// int i=0;
// while(a[i]!='\0')
// {
// i++;
// }
// return i;
int i=0;
while(*a!='\0')
{
a++;
i++;
}
return i;
}
int main()
{
char str1[]="abcdef";
printf("%d\n",Mystrlen(str1));
return 0;
}
b.结果

2. 字符串函数strcmp
(1)strcmp函数
strcmp比较两个字符串的大小,一个字符一个字符比较,按ASCLL码比较
标准规定:
第一个字符串大于第二个字符串,则返回大于0的数字
第一个字符串等于第二个字符串,则返回0
第一个字符串小于第二个字符串,则返回小于0的数字
(2)strcmp函数的使用
a.代码
strcmp的使用
int main()
{
char *p1="abcdef";
char *p2="abcdef";
char *p3="abcd";
char *p4="bcde";
printf("%d\n",strcmp(p1,p2));
printf("%d\n",strcmp(p1,p3));
printf("%d\n",strcmp(p3,p4));
}
b.结果

(3)模拟实现strcmp函数
a.代码
int Mystrcmp(char *a,const char *b)
{
// //数组写法
// int i=0;
// while(a[i]=b[i]&&a[i]!='\0')
// {
// i++;
// }
// return i;
//指针写法
while(*a==*b&&*a!='\0')
{
a++;
b++;
}
return *a-*b;
}
int main()
{
char *p1="abcdef";
char *p2="abcdef";
char *p3="abcd";
char *p4="bcde";
printf("%d\n",Mystrcmp(p1,p2));
printf("%d\n",Mystrcmp(p1,p3));
printf("%d\n",Mystrcmp(p3,p4));
}
b.结果

3.字符串函数strcpy
(1)strcpy函数

把source的字符拷贝到destination,且必须考虑destination的空间够不够
(2)strcpy函数的使用
a.代码
#include<stdio.h>
#include<string.h>
int main()
{
char p1[]="abcdefgh";
char p2[]="hello";
strcpy(p1,p2);
printf("%s\n",p1);
printf("%s\n",p2);
}
b.结果

(3)模拟实现strcpy函数
a.代码
#include<stdio.h>
int Mystrcpy(char *a,const char *b)
{
int i=0;
//数组写法
// while(b[i]!='\0')
// {
// a[i]=b[i];
// i++;
// }
// a[i]='\0';
//指针写法
while(*b!='\0')
{
*a=*b;
a++;
b++;
}
*a='\0'
;}
int main()
{
char p1[]="abcdefsdawdadS";
char *p2="hello";
Mystrcpy(p1,p2);
printf("%s\n",p1);
printf("%s\n",p2);
}
b.结果

4.字符串函数strcat
(1)strcat函数

把source拷贝到destination后面,接成一个长的字符串,同时destination必须具有足够的空间
(2)strcat函数的使用
a.代码
#include<stdio.h>
#include<string.h>
int main()// strcat的用法
{
char p1[] = "hello ";
char p2[] = "world";
strcat(p1, p2);
printf("%s\n", p1);
printf("%s\n", p2);
}
b.结果

( 3)模拟实现strcat函数
a.代码
#include<stdio.h>
#include<string.h>
int Mystrcat(char *a,char *b )
{ //数组写法
// int i=0;
// //让a指向'\0'位置
// while(a[i]!='\0')
// {
// ++i;
// }
// int j=0;
// //让a从'\0'开始将b赋值给a
// while(b[j]!='\0')
// {
// a[i]=b[j];
// i++;
// j++;
// }
// a[i]='\0';
//指针写法
while(*a!='\0')
{
a++;
}
while(*a=*b)
{
a++;
b++;
}
*a='\0';
}
b.结果

5.总结
char *一般用于动态分配空间或者处理参数,用于处理一个字符串
char []一般用于构造一个字符串
如果要对字符串进行修改应该用数组.
本文详细介绍了C语言中四个重要的字符串处理函数——strlen用于计算字符串长度,strcmp用于比较字符串,strcpy用于复制字符串,strcat用于连接字符串。文中不仅展示了函数的标准使用方法,还提供了模拟实现这些函数的代码示例,帮助读者深入理解其工作原理。
3469

被折叠的 条评论
为什么被折叠?



