版权声明:转载请注明出处 https://blog.csdn.net/nanhuaibeian/article/details/87566715
目录
1. 字符数组定义及初始化
//不预定数组长度,根据提供的初值,自动
char c[] = {"I love C"};
//预定数组长度
char c[100] = {"I love C"};
2. 字符串和字符串结束标志
- C语言中是将字符串作为字符数组来处理的
- 存储字符数组常量常自动加一个
\0
作为结束符,程序中往往依靠检测\0
的位置来判定字符串是否结束,而不是根据数组的长度 - 字符数组并不要求它的最后一个字符为
\0
,甚至可以不包括\0
,,是否需要加\0
,完全根据需要决定
3. 字符数组的输入输出
- 逐个字符输入输出,用个个格式符%c输入或输出一个字符
#include <stdio.h>
int main()
{
char s;
scanf("%c",&s);
printf("%c",s);
return 0;
}
- 将整个字符串一次输入或输出。用%s格式符,意思是对字符串的输入输出
#include <stdio.h>
int main()
{
char s[100];
scanf("%s",s);
printf("%s",s);
return 0;
}
因此可以这样处理
4. 使用字符串处理函数
注意:使用字符串处理函数要加上头文件 #include <string.h>
(1)gets函数:输入字符串的函数
(2)puts函数:输出字符串的函数
(3)strcat函数:字符串连接函数
#include <stdio.h>
#include <string.h>
int main()
{
//字符串数组s1必须足够大,以便容纳连接后的新字符串,也就是必须声明足够大的长度
char s1[100] = {"I "};
char s2[] = {"love python"};
printf("%s",strcat(s1,s2));
return 0;
}
(4)strcpy和strncpy函数:字符串复制函数
#include <stdio.h>
#include <string.h>
int main()
{
//字符数组s1和字符数组s2必须定义的足够大,而且必须给定长度值
char s1[100],s2[50],s3[]= {"python"};
//将字符串s3中的字符串复制到s1中
strcpy(s1,s3);
printf("%s\n",s1);
//使用strncpy函数将字符串s3中前3个字符复制到字符串数组s2中
strncpy(s2,s3,3);
printf("%s",s2);
return 0;
}
(5)strcmp函数:字符串比较函数
strcmp(字符串1,字符串2)
比较结果:
如果字符串1=字符串2,则函数值为0
如果字符串1>字符串2,则函数值为正整数
如果字符串1<字符串2,则函数值为负整数
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = {"abc"},s2[] = {"abd"};
if(strcmp(s1,s2)>0)
printf("yes");
else printf("NO");
return 0;
}
(6)strlen函数:测字符串长度的函数
(7)strlwr函数:转换为小写的函数
(8)strupr函数:转换为大写的函数
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = {"abc"},s2[] = {"ABC"};
printf("%d\n",strlen(s1));
printf("%s\n",strlwr(s2));
printf("%s\n",strupr(s1));
return 0;
}