注意:使用字符串函数时,需要添加头文件#include <string.h>
编译器:DEV C++
一、统计字符串长度函数 strlen(串首地址) /*解释串首地址:数组的名*/
作用:计算有效字符个数
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="china";
printf("%d",strlen(s));
}
输出结果 (无符号整数):5 /*china字符串长度为5*/
二、字符串拷贝函数 strcpy(串1首地址符,串2首地址符)
作用:将串2连同结束符一起从串1的0下标位置开始覆盖
例1、简单的两个字符串覆盖
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="china";
char t[10]="123";
strcpy(s,t);/*s为串1首地址,t为串2首地址*/
puts(s);
}
输出结果:123(“china”被“123”所覆盖)
例2、字符串间交换
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="china";
char t[10]="123";
char k[10] ; /*空数组做中间值*/
strcpy(k,s); /*k被s覆盖*/
strcpy(s,t); /*s被t覆盖*/
srtcpy(t,k); /*t被k覆盖*/
puts(s);
puts(t);
}
输出结果:123 china
三、字符串拼接 strcat(串1首地址符,串2首地址符)
作用:将串2连同结束符一起从串1的结束符位置开始向后覆盖
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="china";
char t[10]="123";
strcat(s,t); /*调用strcat函数*/
puts(s);
}
输出结果:china123
四、字符串的比较 strcmp(串1首地址符,串2首地址符)
作用:将两个串从下标0位置开始并对齐,两两进行比较首字符的ASCII值,若要相同,则一次向后顺延比较,知道比出大小;一旦不同,则停止后面的比较。
输出值的几种情况:
(1)、串1>串2时---->1
(2)、串1<串2时---->-1
(3)、串1=串2时----->0
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="china";
char t[10]="123";
if(strcmp(s,t)>0)
printf("大于");
else
printf("小于");
}
输出结果:大于
五、字符串字母大小写转换函数 注:不适用于指针变量
a、大写转小写 strlwr(数组首地址)
b、小写转大写 sreupr(数组首地址)
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="china";
strupr(s);
puts(s);
}
输出结果:CHINA
大写转小写
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="CHINA";
strlwr(s);
puts(s);
}
输出结果:china
六、字符串倒置函数 strrev(数组首地址)
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10]="abcde";
strrev(s);
puts(s);
}
输出结果:edcba