关于字符串的函数总结:strlen(),strcmp(),strcpy(),strcat()
1.strlen() 函数
size_t strlen(const char* s)
返回s的字符串长度,不包括结尾的0
#include <stdio.h>
#include <string.h>
//对于字符数组遍历,比较重要的一个点就是,看看是不是走到结尾遇到 '\0',
int myStrlen(char *size){
int count=0;
//*size,这是用指针的方法来做的
while(*size!='\0'){//对数组进行遍历,但不知道大小,可以用while循环,找到大小用for循环
count++;
size++;
}
return count;
}
int main(int argc,char const *argv[]){
char s[]="hello world";
printf("myStrlen(s)=%d\n",myStrlen(s)); //11,这是自定义的函数,实现strlen()函数的功能
printf("strlen(s)=%d\n",strlen(s));//字符串长度11 ,不包括结尾的那个 \0
printf("sizeof(s)=%d\n",sizeof(s));//数组大小为12
return 0;
}
#include <stdio.h>
#include <string.h>
//strcmp(s1,s2); s1==s2,返回0,大于返回1 ,小于返回-1
int main(int argc,char const *argv[]){
char s1[]="cbc";
char s2[]="bbc";
printf("%d\n",strcmp(s1,s2)); //相当于s1-s2
return 0;
}
2.自定义实现strcmp()函数的功能:
int strcmp(const char* s1,const char* s2);
比较两个字符串,返回值:
0: s1==s2
1:s1>s2
-1:s1<s2
(1)用指针实现的:
#include <stdio.h>
#include <stdlib.h>
//int strcmp(const char* s1,const char* s2);
//比较两个字符串,返回:
// 0: s1==s2
// 1:s1>s2
//-1:s1<s2
int mycmp(const char* s1,const char*s2){
while(*s1==*s2&&*s1!='\0'){
s1++;
s2++;
}
return *s1-*s2;
}
int main(int argc,char const *argv[]){
char s1[]="abc";
char s2[]="abc ";
printf("mycmp=%d\n",mycmp(s1,s2));//-32,等于 '\0'-' ',看下面两行
// printf("%d\n",strcmp(s1,s2));
printf("%d\n", ' ');// 空格等于32
printf("%d\n", '\0');// '\0'等于0
return 0;
}
(2)用数组实现的:
#include <stdio.h>
#include <string.h>
//自定义实现函数strcmp的功能,用数组实现的
int myStrcmp(const char *s1,const char *s2){
int idx=0;
while(s1[idx]!=s2[idx]&&s1[idx]=='\0'){
break;
}
idx++;
return s1[idx]-s2[idx];
}
int main(int argc,char const *argv[]){
char s1[]="hello world";
char s2[]="hello world";
printf("%d\n",myStrcmp(s1,s2));
return 0;
}
3.strcpy()函数
功能:复制一个字符串;
char* dst=(char*) malloc(strlen(src)+1);
strcpy(dst,src);
#include <stdio.h>
#include <string.h>
//实现strcpy的功能
//strcpy()函数
// char* strcpy(char* restrict dst,const char* restrict src);
//把src的字符串拷贝到dst
// restrict表明src和dst不重叠
//返回dst
char* myStrcpy(char* dst, const char* src){
//int idx=0; 这是数组实现,下面是指针实现
//while(src[idx]!='\0'){
// dst[idx]=src[idx];
// idx++;
//}
//dst[idx]='\0';
char* ret=dst;//指针实现
while(*src!='\0'){
*dst++=*src++;
}
*dst='\0';
return ret;
}
int main(int argc,char const *argv[]){
char s1[]="hello";
char s2[]="world 1";
//strcpy(s1,s2);
printf("%s\n",myStrcpy(s1,s2));
return 0;
}