第10讲 字符数组和字符串.ppt
文本预览下载声明
上讲回顾;一、字符数组;3.字符数组的引用;4.字符串和字符串结束标志;5.字符串(字符数组)的输入输出 ;说明
数组名表示数组的首地址;
用“%s”格式符输出字符串时,printf函数中的输出项是字符数组名,而不是数组元素名。
如果数组长度大于字符串实际长度,也只输出到遇′\0′结束。
输出字符不包括结束符′\0′。、
如果一个字符数组中包含一个以上′\0′,则遇第一个′\0′时输出就结束。
;puts函数 字符串的输出
其一般形式为: puts(字符数组)
其作用是将一个字符串(以′\0′结束的字符序列)输出到终端。假如已定义str是一个字符数组名,且该数组已被初始化为China。则执行puts(str);其结果是在终端上输出China。;gets函数 字符串的输入
其一般形式为:gets(字符数组)
其作用是从终端输入一个字符串到字符数组,并且得到一个函数值。该函数值是字符数组的起始地址。如执行下面的函数:
gets(str)
从键盘输入:
Computer↙将输入的字符串Computer送给字符数组str;注意
用puts和gets函数只能输入或输出一个字符串,不能写成puts(str1,str2)或 gets(str1,str2) ;//例:gets,puts
#includestdio.h
void main()
{
char str[30];//定义一字符数组
gets(str);//得到一字符串
puts(str);//输出字符串
};strcat函数 字符串的连接
其一般形式为:strcat(字符数组1,字符数组2)
strcat的作用是连接两个字符数组中的字符串,把字符串2接到字符串1的后面,结果放在字符数组1中,函数调用后得到一个函数值——字符数组1的地址。;//例:strcat
#includestdio.h
void main()
{
char str1[30],str2[20];
puts(please intput the string1:);
gets(str1);
puts(please intput the string2:);
gets(str2);
strcat(str1,str2);
puts(The final string is:);
puts(str1);
};strcpy函数 字符串的复制
其一般形式为:strcpy(字符数组1,字符串2)
strcpy是“字符串复制函数”。作用是将字符串2复制到字符数组1中去。例如:
char str1[10],str2[]={″China″};
strcpy(str1,str2); ;关于strcpy函数的几点说明;例://strcpy
#includestdio.h
void main()
{
char str1[30],str2[20];
puts(please intput the string:);
gets(str2); //得到字符串str2
strcpy(str1,str2); //将str2复制到str1中
puts(The string1 is:);
puts(str1); //输出str1
};//strncpy
#includestdio.h
void main()
{
char str1[30],str2[20];
puts(please intput the string1:);
gets(str1);
puts(please intput the string2:);
gets(str2);
strncpy(str1,str2,3); //将str2的前3个字符替代str1的前三个字符
puts(The string1 is:);
puts(str1);
};strcmp函数
其一般形式为:strcmp(字符串1,字符串2)
strcmp的作用是比较字符串1和字符串2。
例如:strcmp(str1,str2);
strcmp(″China″,″Korea″);
strcmp(str1,″Beijing″);;比较的结果由函数值带回
(1) 如果字符串1=字符串2,函数值为0。
(2) 如果字符串1字符串2,函数值为一正整数。
(3) 如果字符串1字符串2,函数值为一负整数。
注意:对两个字符串比较,不能用以下形式:
if(str1str2) printf(″yes″);
而只能用
if(strcmp(str1,str2)0) printf(″yes″);;strlen函数
其一般形式为:strlen (字符数组)
strlen是测试字符串长度的函数。函数的值为字符串中的实际长度(不包括′\0′在内)。
例如:char str[10
显示全部