一.字符串是什么
存放字符(char
)的数组称为字符数组。在C语言中,使用NULL
字符('\0'
)终止的一维字符数组被称作字符串。
二.字符串怎么用
1.初始化
char 字符串变量名[字符数量] = {字符1,字符2,....,'\0'};
也可更简便,eg.
char greeting[] = "Hello World";
注:初始化没有初始化时,应手动声明arr[n](字符串末尾)='\0'
2.输入输出
使用scanf()函数和printf()函数,但占位符是%s
3.访问字符
跟数组一样
#include <stdio.h>
int main(){
char name[20];
printf("请输入你的名字:");
scanf("%s",name);
printf("你好,%s\n",name);
}
4.赋值
char s[]="Hello World";
char t[20];
t = s;
①遍历:
for(int i=0;'\0'!=s[i];++i){
t[i] = s[i];
}
②函数strcpy():
strcpy(t,s);
例:输入一个年月日时分秒组成的数字,按照XXXX年XX月XX日XX时XX分XX秒打印出来。例如:输入20190311180301,打印出2019年3月11日18时3分1秒。
#include<stdio.h>
int main(){
//char date[15];
//scanf("%s",&date);
//20211016162155
char year[5];
char month[3];
char day[3];
char hour[3];
char minute[3];
char second[3];
scanf("%4s%2s%2s%2s%2s%2s",&year,&month,&day,&hour,&minute,&second);
printf("%s年%s月%s日%s时%s分%s秒",year,month,day,hour,minute,second);
}
%4s 指取4位