1.strlen函数
原型:strlen(str);
功能:计算字符串str的长度
返回:一个int值
注意字符串的长度不包括字符'\0'
//获取字符串的长度 :strlen
#include<stdio.h>
#include<string.h>
int main()
{
char str[]="I love Fishc.com!";
printf("sizeof str=%d\n",sizeof(str));
printf("sizeof str=%u\n",strlen(str));
return 0;
}
运行结果:
sizeof str=18
sizeof str=17
--------------------------------
Process exited after 0.1186 seconds with return value 0
请按任意键继续. . .
2.strcpy函数
原型:strcpy(str1,str2);
功能:将字符串str2复制到字符串str1中,并覆盖str1原始字符串,可以用来位字符串变量赋值
返回:str1
注意1.字符串str2会覆盖str1中的全部字
2.字符串str2的长度不能超过str1
//拷贝字符串:strcpy和strncpy
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]="I love Fishc.com!";
char str2[]="New string";
char str3[100];
strcpy(str1,str2);
strcpy(str3,"Copy Successful");
printf("str1:%s\n",str1);
printf("str2:%s\n",str2);
printf("str3:%s\n",str3);
return 0;
}
运行结果:
str1:New string
str2:New string
str3:Copy Successful
--------------------------------
Process exited after 0.1028 seconds with return value 0
请按任意键继续. . .
strncpy函数
原型:strncpy(str1,str2,n)
功能:将字符串str2中前n个字符复制到字符串str1的前n个字符中
返回:str1
注意1.不会清楚str1中全部字符串,只会改变前n个字符串
2.n不能大于字符串str1、str2的长度
//拷贝字符串:strcpy和strncpy
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]="I love Fishc.com!";
char str2[]="New string";
strncpy(str2,str1,5);
str2[5]='\0';
printf("str1:%s\n",str1);
printf("str2:%s\n",str2);
return 0;
}
运行结果:
str1:I love Fishc.com!
str2:I lov
--------------------------------
Process exited after 0.1131 seconds with return value 0
请按任意键继续. . .
3.strcat函数和strncat函数
原型:strcat(str1,str2);
功能:将字符串str2添加到字符串str1的尾部,也就是拼接两个字符串
原型:strncat(str1,str2,n);
功能:将字符串str2的前n个字符添加到字符串str1的尾部
返回:str1
注意:拼接之后的长度不能超过字符串数组str1的长度
//连接字符串 :strcat和strncat
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]="I love ";
char str2[]="xiangongda!";
strcat(str1,"");
strcat(str1,str2);
printf("str1:%s\n",str1);
return 0;
}
运行结果:
str1:I love xiangongda!
--------------------------------
Process exited after 0.1066 seconds with return value 0
请按任意键继续. . .
4.strcmp函数和strncmp函数
原型:strcmp(str1,str2);
功能:比较两个字符串,如果两个字符串相等,则返回0;若str1大于str2(对于大于的理解,是指从两个字符串的第一个字符开始比较,若两个字符相同,则继续比较,若发现两个字符不相等,且str1中该字符的ASCII码大于str2中的,则表示str1大于str2),返回一个正数(这个正数不一定是1);若str1小于str2,返回一个负数(不一定是-1);若字符串str1的长度大于str2,且str2的字符与str1前面的字符相同,则也相对于str1大于str2处理
原型:strncmp(str1,str2,n);
功能:比较两个字符串的前n个字符
原型:stricmp(str1,str2); (在Windows中使用stricmp,在Linux中使用strcasecmp)
功能:忽略两个字符串中的大小写比较字符串,也就是对大小写不敏感
//比较字符串 :strcmp和strncmp
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]="I love ";
char str2[]="xiangongda!";
if(!strcmp(str1,str2))
{
printf("两个字符串完全一致!\n");
}
else
{
printf("两个字符存在差异!\n");
}
return 0;
}
运行结果:
两个字符存在差异!
--------------------------------
Process exited after 0.1183 seconds with return value 0
请按任意键继续. . .