1、字符输⼊输出:
putchar()与getchar()
int putchar(int c):向标准输出写⼀个字符 ,返回写了⼏个字符,EOF(-1)表⽰写失败
int getchar(void): 从标准输⼊读⼊⼀个字符,返回类型是int是为了返回EOF(-1)
Windows—>Ctrl-Z 结束输入
Unix—>Ctrl-D 结束输入
int ch;
while((ch=getchar())!=EOF){
putchar(ch);
}
printf("EOF\n");
2.strlen():返回s的字符串⻓度(不包括结尾的0):
strlen()的实现:
int mylen(const char *s){
int cnt;
while(*s++!='\0'){
cnt++;
}
return cnt;
}
运行结果:
3.strcmp():字符串比较
int strcmp(const char *s1, const char *s2);
⽐较两个字符串,返回:
• 0:s1==s2
• >0:s1>s2
• <0:s1
strcmp()的两种实现方式:(一种通过数组,一种通过指针)
int mycmp(const char *s1,const char *s2){
int idex=0;
while(1){
if(s1[idex]!=s2[idex]){
break;
}else if(s1[idex]=='\0') {
break;
}
idex++;
}
return s1[idex]-s2[idex];
}
int mycmp1(const char *s1,const char *s2){
while(*s1==*s2&&*s1!='\0'){
s1++;
s2++;
}
return *s1-*s2;
}
运行结果:
4.strcpy ():字符串拷贝
• char * strcpy(char *restrict dst, const char *restrict src);
• 把src的字符串拷⻉到dst
• restrict表明src和dst不重叠(C99)
• 返回dst
实现代码:
char* mycpy(char *dst,const char *src){
int idex=0;
while(src[idex]!='\0'){
dst[idex]=src[idex];
dst++;
src++;
}
dst[idex]=src[idex];
}
5.strcat():字符串连接
char * strcat(char *restrict s1, const char *restrict s2);
• 把s2拷⻉到s1的后⾯,接成⼀个⻓的字符串
• 返回s1 , s1必须具有⾜够的空间
安全问题:
复制和连接都会出现空间不够的溢出问题
• char * strncpy(char *restrict dst, const char *restrict src, size_t n);
• char * strncat(char *restrict s1, const char *restrict s2, size_t n);
• int strncmp(const char *s1, const char *s2, size_t n);
6.字符串查找:
字符串中找字符
• char * strchr(const char *s, int c);
• char * strrchr(const char *s, int c);
• 返回NULL表⽰没有找到
7.对hello进行字符串部分复制
分别对he和llo进行复制:
8.字符串中找字符串
• char * strstr(const char *s1, const char *s2):字符串里寻找字符串
• char * strcasestr(const char *s1, const char *s2);不区分大小写寻找字符串