写在前面:C语言中没有String类型!!!
10.1.1
- 以0结尾的一串字符,0或'\0'是一样的,但是和'0'不同。
- 字符串变量的定义方法:
- char * str="hello";
- char word[]="hello";
- char line[10]="hello"; 其结尾均有自动补上的'\0'('\0'占一个字符)
- C语言中两个字符串连接的方法,直接用双引号连接,没有运算符对字符串做运算。
10.1.2
- 构造一个字符串用数组方式 char word[]="hello";
- 处理一个字符串用指针方式 char * str = "hello";
- 字符串可以表达为char*,但是char*不一定是字符串,可能是指针指向单个字符。
10.1.3
- 安全的输入
char string[8];
scanf("%7s",string);
在%和s之间的数字表示最多允许读入的字符的数量,这个数字应该比数组大小小一。
- char buffer [100]="";
- 这是一个空的字符串
- char buffer []="";
- 这个数组的长度只有1
10.1.4
字符串数组:
- char *month []; 这是一个指针数组,如果往其中赋上字符串就是指向字符串的指针数组。
- char month[] [5]; 这是一个二维数组,如果需要附上字符串的话,每个字符串长度不超过(5-1)位。
#include<stdio.h>
int main(void){
int a;
char *month[]={"jar","feb","mar","apr","may","june","july","aug","sep","oct","nov","dec"};
scanf("%d",&a);
printf("%4s",month[a-1]);
return 0;
}
10.2.1
有关字符串函数:putchar(int a); 原封输出a getchar(void); 返回值是int为了返回EOF
#include<stdio.h>
int main(void){
int ch;
while((ch=getchar())!=EOF){
putchar(ch);
}
printf("EOF");
return 0;
}
10.2.2~10.2.5
#include<string.h>
- strlen(const char *s) 返回字符串的长度
- strcmp(const char*s1,const char*s2) 比较两个字符串的长度(0:s1==s2 1:s1>s2 -1:s1<s2)
- char * strcpy(char *restrict dst, const char* restrict src) 把src的字符拷贝到dst,restrict不能重叠(C99,不能在原有的基础上覆盖)
<3>常用套路,复制一个字符串(记得+1)
char *dst= (char*)malloc(strlen(src)+1);
strcpy(dst,src);
4.char*strcat(char*restrict s1,const char *restrict s2) 把s2拷贝到s1的后面,接成长字符串,返回s1,(s1必须拥有足够空间)
5.char *strchr(const char*s,int c) 把c之后的字符串输出。c可以为'a'。
char* strrchr(const char*s,int c)