Character functions and string functions (on)

Find the length of the string

1.strlen

size_t strlen(const char* str)

  • The string ends with '\0', and the strlen function returns the number of characters that appear before '\0' in the string (not including

Contains '\0' )

  • The string pointed to by the parameter must end with '\0'

  • Note that the return value of the function is size_t, which is unsigned

Below is the code directly (simulating the strlen function):

In this arr array, there are mainly four elements of bit \0, so we let our * str move backwards in the my_strlen function until the end of \0. This is what we are simulating the strlen function, which ends with \0 flag, count the number of elements before \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)

  • The source string must be terminated with '\0'.

  • Will copy '\0' in the source string to the destination space.

  • The destination space must be large enough to hold the source string

  • The target space must be mutable.

Here we explain: strcpy (purpose function, source function)

So in the strcpy function, we can know that \0 can be copied in the strcpy function

Error demonstration: (the target space must be large enough)

In this array, arr2 can only store 3 elements, and we have elements such as abcdefghi \0 in arr1, so the elements of arr1 cannot be placed in arr2, resulting in an error


3. broken

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中元素的地址


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

Guess you like

Origin blog.csdn.net/m0_74459304/article/details/129507684