c语言:字符串函数

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);不区分大小写寻找字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值