前言
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