[Advanced C Language] Character functions and string functions, take you to master the core usage and simulate the implementation (1) - strlen, strcpy, strcmp

insert image description here

Junxi_'s personal homepage

Be diligent and encourage the years to wait for no one

C/C++ game development


Hello, Mina-san, this is Junxi_, and I took the time to update you again today. The content I bring today is the usage of character functions and string functions and attention to details, and I will take you to simulate and implement all the key points. Since this part has a lot of content, we will talk about it several times. This is the first article.
Well, without further ado, let's start today's study!

foreword

The processing of characters and strings in C language is very frequent, but C language itself does not have a string type, and strings are usually placed in
constant strings or character arrays.
Among them, the string constant applies to those string functions that do not modify it

  • Let's first briefly understand these character/string functions through a mind map
    insert image description here
  • Well, let's introduce them one by one!

1. The function strlen to find the length of a string

size_t strlen ( const char * str );
  • 1. We know that the string ends with '\0', and the strlen function returns the number of characters that appear before '\0' in the string (excluding '\0').
  • 2. The string pointed to by the parameter must end with '\0'.
    For example, the following string, strlen cannot calculate its length
char arr[10]={
    
    'a','b','c'}//没有\0作为结束标志
  • Note: The return value of the function is size_t, which is unsigned (error-prone)
    Let's look at the following example
#include <string.h>
#include <string.h>

int main()
{
    
    
	if (strlen("abc") - strlen("abcdef") > 0)
	{
    
    
		printf("大于\n");
	}
	else
	{
    
    
		printf("小于等于\n");
	}

	return 0;
}

insert image description here

  • Many beginners often feel confused when encountering similar programs. It is obvious to us that "abc" must be smaller than "abcdef", so why does our compiler judge that it is greater than?
  • look here,
size_t strlen ( const char * str );
  • size_t是一个无符号数,也就是说无论谁大谁小都会返回一个大于0的数,因此打印在屏幕上的结果一定是大于.
  • If we want the program to run correctly, we can modify it like this
if ((int)strlen("abc") - (int)strlen("abcdef") > 0)

insert image description here

  • However, there is a certain irrationality here. We know that calculating the length of a string must return a number greater than 0, that is, an unsigned number (this is also the reason why the return value of strlen is set to size_t in the library function), but the int here is a signed number.
  • 总的来说,两者都有利有弊,在我们实际应用时根据需要选择返回值类型即可

1. Simulate the implementation of the strlen function

The common method is relatively simple. If you want to learn, you can try it yourself. Here I bring you two more advanced methods to show you how to implement the strlen function. Of course, if you understand these two methods, you can write the normal method casually.

Realize strlen function with recursion

//递归的形式实现
int my_strlen(char* arr)
{
    
    
    if (*arr)
        return 1 + my_strlen(arr+1);//每递归一次+1,直至*arr指向\0

}
int main()
{
    
    

    char arr[] = "abcdefgh";
    int ret = my_strlen(arr);
    printf("%d", ret);
    return 0;
}

insert image description here

pointer-pointer method implementation

//指针-指针的形式
int my_strlen(char*arr)
{
    
    
    char* p1 = arr;
    while (*p1)
    {
    
    
        p1++;
    }
    return p1 - arr;//通过最后一个元素减去首元素得到字符串大小
}
int main()
{
    
    

    char arr[] = "abcdefgh";
    int ret = my_strlen(arr);
    printf("%d", ret);
    return 0;
}

insert image description here

  • Is it very simple? we continue

Two. Copy function strcpy

char* strcpy(char * destination, const char * source )
  • Among the two parameters passed in, the first parameter is the destination address, and the second parameter is the source address. The purpose of our strcpy function is to copy the string in the source address to the destination address.
  • Among them, the source string must end with '\0'.
  • strcpy will copy the '\0' in the source string to the target space.
  • The destination space must be large enough to accommodate the source string.
  • The target space must be mutable.
#include<string.h>
int main()
{
    
    
    char arr1[] = {
    
     "Hello,World" };
    char arr2[20] = {
    
     0 };//此处目的地中初始化必须指定空间大小
    strcpy(arr2, arr1);
    printf("%s", arr2);
    return 0;

}

insert image description here


Simulate the implementation of the strcpy function

#include<assert.h>
void my_strcpy(char* p1, const char* p2)
{
    
    
    assert(p1 && p2);//先断言保证p1,p2都不是空指针
        while (*p1 = *p2)//把源头元素赋给目的地,直至遇到\0;
        {
    
    
            p1++;
            p2++;
    }

}


int main()
{
    
    
    char arr1[] = {
    
     "Hello,World" };
    char arr2[20] = {
    
     0 };
    my_strcpy(arr2, arr1);
    printf("%s", arr2);
    return 0;

}

insert image description here

  • Is it not too difficult? Then let's continue!

3. Compare string size function strcmp

int strcmp ( const char * str1, const char * str2 );
  • standard regulation:
    第一个字符串大于第二个字符串,则返回大于0的数字
    第一个字符串等于第二个字符串,则返回0
    第一个字符串小于第二个字符串,则返回小于0的数字
  • So how to compare string size in C language?

1. String comparison size rules

  • For comparing the size of two character strings, it is actually comparing the size of the ASCLL code value of the character at the corresponding position. If the ASCLL value at the same position is the same, compare the next position until there is a difference.
  • For example the following code
    insert image description here
  • We know that the ascll code value of 'z' is greater than that of 'l', so a number greater than 0 is returned. The comparison logic of the strcmp function is that once the elements in the same position of the two compared strings differ, strcmp will stop and return the value
  • Note: The 1 returned here does not mean that it is greater than a certain return 1, but it will vary depending on the compiler. Don’t understand it as a certain return 1 here.

2. Simulate the implementation of the strcmp function

#include<string.h>
#include<assert.h>
int my_strcmp(const char* p1, const char* p2)
{
    
    
    assert(p1 && p2);
    while (*p1 == *p2)
    {
    
    
        if (*p1=='\0')//当走到\0时发现两者依旧相等,说明两者是真的相等
            return 0;
        p1++;
        p2++;
    }
    return *p1 - *p2;//返回值大于0,p1>p2,返回值小于0,p1<p2


}
int main()
{
    
    
    char arr1[10] = "zhangsan";
    char arr2[10] = "zhangsan";
    int ret =my_strcmp(arr1, arr2);
    printf("%d", ret);
    return 0;
}

insert image description here


Summarize

  • This is the end of today's content. Today we first introduced three functions strlen, strcpy and strcmp and simulated and implemented these three functions respectively. If possible, I hope you can do it yourself. This will often give you a deeper understanding.

  • Well, if you have any questions, please ask me in the comment area or private message, see you next time!

It is not easy for a new blogger to create. If you feel that the content of the article is helpful to you, you may wish to click on this new blogger before leaving. Your support is my motivation to update! ! !

**(Ke Li asks you to support the blogger three times in a row!!! Click the comment below to like and collect to help Ke Li)**

insert image description here

Guess you like

Origin blog.csdn.net/syf666250/article/details/131754454