7.3 字符数组
引用:
char 数组名[数组大小];
1.字符串处理,即文本处理
(1)在字符串末尾自动加"\0",表示字符串的结束;
(2)可写成char s[100] = "hello";
2。字符串处理函数
① puts(字符数组)
其作用是将一个字符串(以'\0'结束的字符序列)输出到终端;
②gets(字符数组)
其作用是从终端输入一个字符串到字符数组,并且得到一个函数值。该函数值是字符数组的起始地址。不能检测输出字符是否超过数组容量;
③fgets(数组名,sizeof(数组名),stdin)
其作用是从终端输入一个字符数组,会多输出一个字符'\n';
3算法:不能直接使用运算符。
(1)有效字符的个数,计算字符串长度
①代码表示
#include<stdio.h>
int main(void)
{
char s[100] = "china";
int i = 0;
while(s[i] != 0)
{
++i;
}
printf("%d\n",i);
return 0;
}
②函数
#include<stdio.h>
#include<string.h>
int main(void)
{
char s[100] = "china";
printf("%lu\n"strlen(s));
return 0;
}
(2)数组拷贝
①代码表示
#include<stdio.h>
int main(void)
{
char s1[100] = "china";
char s2[100];
int i;
while(s1[i] != '\0')
{
s2[i] = s1[i];
++i;
}
s2[i] = '\0';
puts(s2);
return 0;
}
②函数表示
#include<stdio.h>
#include<string.h>
int main(void)
{
char s1[100] = "china";
char s2[100];
strcpy(s2,s1);
puts(s2);
return 0;
}
注:目标数组大小需足够大,至少为"strlen(源数组) + 1"
(3)连接两个数组
①代码表示
#include<stdio.h>
int main(viod)
{
char s1[100] = "hello";
char s2[100] = "china";
int i =0,j =0;
while(s1[i] != '\0')
{
++i;
}
while(s2[j] != '\0')
{
s1[i] = s2[j];
++i;
++j;
}
s1[i] = '\0';
puts(s1);
return 0;
}
注:目标数组大小需足够大,至少为"strlen(目标数组)+strlen(源数组) + 1"
②函数表示
#include<stdio.h>
#include<string.h>
int main(void)
{
char s1[100] = "hello";
char s2[100] = "china";
strcat(s1,s2);
puts(s1);
return 0;
}
(4)字符串比较
①代码表示
#include<stdio.h>
#include<string.h>
int main(void)
{
char s1[100] = "hello";
char s2[100] = "china";
int i = 0;
while(s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0')
{
++i;
}
printf("%d",s1[i] - s2[i]);
return 0;
}
②函数表示
#include<stdio.h>
#include<string.h>
int main(void)
{
char s1[100] = "hello";
char s2[100] = "china";
printf("%d\n",strcmp(s1,s2));
return 0;
}
若返回值>0,则s1>s2;若返回值=0,则s1 == s2;若返回值<0,则s1<s2;
(5)求极值
#include<stdio.h>
#include<string.h>
int main(void)
{
char a[100] = "china";
char b[100] = "hello";
char c[100] = "world";
char max[100] ;
if(strcmp(a,b) > 0)
{
strcpy(max,a);
}
else
{
strcpy(max,b);
}
if(strcmp(max,c) < 0)
{
strcpy(max,c);
}
puts(max);
return 0;
}
(6)逆序
#include<stdio.h>
#include<string.h>
int main(void)
{
char s[100] ="china";
int i;
for(i = 0;i < strlen(s)/2;++i)
{
char t;
t = s[i];
s[i] = s[strlen(s) - i - 1];
s[strlen(s) - i - 1] =t;
}
puts(s);
return 0;}
4.练习
实现一个类似itoa函数的功能,将一个整型数据转换为字符串。例如n=1234,转换的结果存放到一个字符数组中char s[100],输出s后得到"1234".
(1)代码:
#include<stdio.h>
#include<string.h>
int main(void)
{
int a;
scanf("%d",&a);
char s[100];
int i = 0;
while(a != 0)
{
s[i] = a % 10 +'0';
++i;
a /=10;
}
s[i] = '\0';
int len = strlen(s);
int j;
for(j = 0;j < len/2;++j)
{
char t;
t = s[j];
s[j] = s[len - j - 1];
s[len - j - 1] = t;
}
puts(s);
return 0;
}
(2)结果: