字符型数组的定义:数据类型 数组名 [元素个数];
eg: char a [10] ;
字符型数组的初始化:
1.全部初始化:
char str[6] = {"hello"}; //默认后面有( \0字符='\0')
char str[6] = "hello";//默认后面有'\0'
char str[6] = {'h', 'e', 'l', 'l', 'o', '\0'};//需要自行添加'\0',也可以不写
2.局部初始化:
char str[6] = {"hel"};//默认后面有'\0'
char str[6] = {'h', 'e', 'l', '\0'};
char str[6] = "hel";
char str[6] = {0};
3.默认初始化(空格可以不用写元素个数):
char str[] = {'h', 'e', 'l', '\0'};
char str[] = {"hel"};//默认后面有'\0'
char str[] = "hel";
字符串的输入:
printf("%s\n",a);(打印数组开头到'\0'中间的所有字符串)
puts(a);(打印数组开头到'\0'中间的所有字符串)
字符串的输入:
sacnf("%s",a);(不能够输入带空格(' ')的字符串)
gets(a);(能够输入带空格(' ')的字符串)
5.字符串操作的函数接口(必须加 #include <string.h>):
字符串拷贝函数:strcpy
eg: strcpy(a,"hello");//把hello拷贝到a字符串中
strcpy(a,b)//把b字符串拷贝到a字符串中
ii. 字符拼接函数: stycat(目的空间需要足够大放入拼接的字符串)
eg: stycat(a,"hello");//把hello拼接到a字符串后
如果a={"hi"};则拼接后为 hihello
iii. 字符串比较函数: stycmp
eg: x=stycmp(a,b);
当x>0时,则a字符串大于b字符串;
当x<0时,则a字符串小于b字符串;
当x=0时,则a字符串等于b字符串;
Ⅳ. 获得字符串的长度: stylen(从字符串开头到\0中间字符的个数(不包含\0,包含空格))
eg: char a[]={"hello world"};
x=strlen(a);
![](https://img-blog.csdnimg.cn/img_convert/35d393e0a26d80d4d2a8a3cdc320e36d.png)
![](https://img-blog.csdnimg.cn/img_convert/cdbf4f41ec19ad5226beb23a70dc8634.png)
注意:
strlen和sizeof的区别
sizeof:获得一个变量或数据类型在内存所占字节
strlen:获得数组中存放的字符串长度
Ⅴ.对字符串元素遍历(可理解为每个字符走一遍):
char a[]="hello world"
while (a[i] != '\0') //i=0表示从a[0],第一个字符是否为'0',如果不是则i++,否则跳出输出i
{
i++;
}
![](https://img-blog.csdnimg.cn/img_convert/1639f7015d6c95d5ac3b78682a3a1713.png)
![](https://img-blog.csdnimg.cn/img_convert/81dea36a453976daf57fe9cba77d2f99.png)
练习(接收用scanf或者gets,输出用printf或者puts):
循环从终端接收字符串,并且打印该字符串,直到用输入"too"循环退出(提醒:字符串相等可用strcmpe+循环+if)
![](https://img-blog.csdnimg.cn/img_convert/b8c69b519dfbc7536361e04c982623fd.png)
![](https://img-blog.csdnimg.cn/img_convert/776274dff6f97b13bdee745e82188700.png)
从终端接收一个字符串,完成字符串的倒置(例如:hello倒置为olleh)(提醒:整型数组倒置的方法,不确定输入长度可用strlen计算,strlen为字符串长度,head,tail为下标,具体看上一章)
![](https://img-blog.csdnimg.cn/img_convert/656b3e095814c42d3f0fb72b79f3990f.png)
![](https://img-blog.csdnimg.cn/img_convert/4dd5fcf76fdeaaef5fd91eb2ad14bc32.png)
从终端接收一个字符串, 统计该字符串中大写字母、小写字母、数字及空格的个数(提醒:ascii码+if+字符串的遍历直至结束遇到'\0')
![](https://img-blog.csdnimg.cn/img_convert/fc20efc2511d8680d5d21050036e24cf.png)
![](https://img-blog.csdnimg.cn/img_convert/355bb228c01946f201ffc8b2c336beee.png)
从终端接收一个字符串存放到a数组中,将其中的字符串拷贝到b数组中(要求不能使用strcpy)(提醒:循环)
![](https://img-blog.csdnimg.cn/img_convert/0fa7b2401220ffda981039fa8f0348bd.png)
![](https://img-blog.csdnimg.cn/img_convert/6dc40240fe27e24d6f4a2dcb24a515c8.png)
5.从终端接收两个字符串存放到数组a和b中,将两个字符串实现拼接(要求不能使用strcat)(提醒:a字符串的最后为'\0',可用字符串遍历来判断,然年再进行拼接)
![](https://img-blog.csdnimg.cn/img_convert/5a7979136b4d317bc7ab74595788be02.png)
![](https://img-blog.csdnimg.cn/img_convert/c28d82bc903dada2b5a0374514f899df.png)