字符函数和字符串函数(上)

求字符串长度

1.strlen

size_t strlen(const char* str)

  • 字符串是以‘\0’结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包

含 '\0' )

  • 参数指向的字符串必须要以 '\0' 结束

  • 注意函数的返回值为size_t,是无符号的

下面直接上代码(模拟strlen函数):

在这个arr数组中主要有b i t \0这四个元素,所以我们在my_strlen函数中让我们的* str一直向后移动,直到\0结束,这个就是我们在模拟strlen函数,是以\0为结束标志,计算\0之前的元素个数


2.strcpy

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

  • Copies the C string pointed by source into the array pointed by destination, including the

terminating null character (and stopping at that point)

  • 源字符串必须以 '\0' 结束。

  • 会将源字符串中的 '\0' 拷贝到目标空间。

  • 目标空间必须足够大,以确保能存放源字符串

  • 目标空间必须可变。

这里我们解释一下:strcpy(目的函数,来源函数)

所以在strcpy函数中,我们可以知道在strcpy函数中\0是可以被拷贝的

错误示范:(目标空间必须足够大)

在这个数组中,arr2只能存入3个元素,而我们arr1中有abcdefghi \0这些元素,所以arr2中放不下arr1的元素,导致错误


3.strcat

char * strcat ( char * destination, const char * source )

  • Appends a copy of the source string to the destination string. The terminating null character

in destination is overwritten by the first character of source, and a null-character is included

at the end of the new string formed by the concatenation of both in destination.

  • 源字符串必须以 '\0' 结束。

  • 目标空间必须有足够的大,能容纳下源字符串的内容。

  • 目标空间必须可修改

这里我们解释一下:在这个函数中我们可以把arr2中的元素存放在arr1元素的后面,而在这个过程中,我们arr1的数组必须足够大,而且是以\0为标志才能存放到源字符串的后面


4.strcmp

int strcmp ( const char * str1, const char * str2 )

  • This function starts comparing the first character of each string. If they are equal to each

other, it continues with the following pairs until the characters differ or until a terminating

null-character is reached.

  • 标准规定:

  1. 第一个字符串大于第二个字符串,则返回大于0的数字

  1. 第一个字符串等于第二个字符串,则返回0

  1. 第一个字符串小于第二个字符串,则返回小于0的数字

strcmp函数中,我们是依次比较元素的ASCII码值的大小,如果arr1中ASCII码值大于arr2中ASCII码值则打印 > 号,反之,如果相等则打印0

这里我们是a与a比较,b与b比较,z与q比较


5.strstr

char * strstr ( const char *str1, const char * str2)

  • Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of

str1

strstr函数中,我们是在arr1中元素找arr2的元素,而这些元素中,我们是找第一次出现的元素,从而打印出arr1中元素的地址


以上就是我们字符函数的上篇,明天后天我会更新出下篇,喜欢的话请三连留下您的关注哦!!!

猜你喜欢

转载自blog.csdn.net/m0_74459304/article/details/129507684