C语言:字符串函数,strlen函数,strcpy函数,strcat函数,strcmp函数,strncpy函数,strncat函数,strncmp函数

前言
C语言中对字符和字符串的处理很是频繁,但是C语言本身是没有字符串类型的,字符串通常放在 常量字符串 中
或者 字符数组 中。 字符串常量 适用于那些对它不做修改的字符串函数.

求字符串长度

strlen

size_t strlen ( const char * str );

1.字符串已 ‘\0’ 作为结束标志,strlen函数返回的是在字符串中 ‘\0’ 前面出现的字符个数(不包含 ‘\0’ )。
2.参数指向的字符串必须要以 ‘\0’ 结束。
3.注意函数的返回值为size_t,是无符号的( 易错 )

模拟实现strlen函数

模拟实现 strlen
#include <stdio.h> 
#include <assert.h>
int my_strlen(const char* str)
{
   
	int count = 0;
	assert(str != NULL);
	while (*str != '\0')
	{
   
		count++;
		str++;
	}
	return count;
}
int main()
{
   
	int len = my_strlen("abcdef");
	printf("%d\n", len);
	return 0;
}

注:

#include <stdio.h> 
int main() 
{
    
const char*str1 = "abcdef"; 
const char*str2 = "bbb"; 
if(strlen(str2)-strlen(str1)>0) 
{
    
printf("str2>str1\n"); 
} 
else 
{
    
printf("srt1>str2\n"); 
} 
return 0; 
}

在这里插入图片描述

长度不受限制的字符串函数(只认’\0’,有一定的缺陷)

strcpy(字符串拷贝)

char* strcpy(char * destination, const char * source );

1.Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
2.源字符串必须以 ‘\0’ 结束。
3.会将源字符串中的 ‘\0’ 拷贝到目标空间。
4.目标空间必须足够大,以确保能存放源字符串。
5.目标空间必须可变。

模拟实现 strcpy函数

模拟实现 strcpy
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值