Detailed explanation of character functions and string functions (1)

foreword

I have to adjust my status recently, and the poor quality of the articles I wrote disappointed everyone. Now I am also reflecting on what I am doing, what I know, and what I have learned. On the day when I figure it out, I will definitely be able to meet you at the summit, and I wish you all the best of luck and respect.
insert image description here
I am also here to thank everyone for your support with a sentence from Kipchoge: "No human is limited." Finally, back to the topic, what we are talking about today is part of the lack of C language, the functions in the <string.h> library , the functions in it have a lot of background, listen to me.

strlen function

Although you see such a few words in this function, it is definitely not advanced. Hey, this function is really amazing. This function has a lot of background. Let me analyze it one by one. After listening to it, you will know the connotation.

size_t strlen ( const char * str );

It can be seen that although the structure of this code is so simple, it is only as important as sizeof in both problem solving and work. So we introduce the difference between the first topic and sizeof

strlen

As a library function, strlen acts on the string with '\0' as the end mark, and the strlen function returns the number of characters that appear before '\0' in the string (excluding '\0'). Someone asked what it meant, why do you need code to solve things that can be solved by talking, the code shows:

#include <stdio.h>
#include <string.h>
int main(){
    
    
    char str[100] = {
    
     0 };
    size_t len;
    gets(str);
    len = strlen(str);
    printf("Length: %d\n", len);
    return 0;
}

insert image description here
In fact, we can also find that strlen finds the number of characters in front of it based on the position of \0. This is the most important and most useful part of strlen. In fact, whether it is in oj questions or practice questions, strlen can help us locate the last element of an array as quickly as possible, and it is better to use it.

#include <stdio.h>
#include <string.h>
#include <assert.h>
 
void reverse(char* left, char* right)   //逆序字符串(整个字符串的逆序)
{
    
    
	assert(left != NULL && right != NULL);
	while (left < right)
	{
    
    
		int ret = *left;
		*left = *right;
		*right = ret;
		left += 1;
		right -= 1;
	}
}
 
int main()
{
    
    
	char arr[100] = {
    
     0 };
	gets(arr);
	int len = strlen(arr);
	reverse(arr, arr + len - 1);
	printf("%s", arr);
	return 0;
}

It is also the simplest and most violent reverse sorting.
Use strlen to find the last element.
Finally, the return type of the strlen function is size_t - unsigned integer

sizeof

The first thing to note is that sizeof is more important because it is not a function, but an operator.
The sizeof operator gives the storage size of its operand in bytes. The operand can be an expression or a type name enclosed in parentheses. The storage size of an operand is determined by the type of the operand.
In fact, simply speaking, the record is the space occupied by the string. It can be said that it can’t be compared with strlen,
but why it is always confused with strlen (I also confuse it). In fact, the most important thing is that I don’t understand the meaning of the two usages. . But after reading this part of me, you will understand a lot

sizeof usage form: sizeof(type)
  data type must be enclosed in parentheses: sizeof(int)

int a=10;
int arr[]={
    
    1,2,3};
char str[]="hello";
int len_a = sizeof(a);
int len_arr = sizeof(arr);
int len_str = sizeof(str);
printf("len_a=%d,len_arr=%d,len_str=%d\n",len_a,len_arr,len_str);

The space occupied by each of the different types is calculated

strcpy function

Copies the C string pointed by source into the array pointed by destination, including theter minating null character (and stopping at that point)
we translate it once is the copy function, so let me list all the functions in English.

char *strcpy(char *dest, const char *src)

Take a brief look, we will find that each string has a '\0', we guess why the copy is over, will the '\0' be copied in, we will simulate it on the computer

int main()
{
    
    
	char str1[] = "Sample string";
	char str2[40];
	char str3[40];
	strcpy(str2, str1);
	strcpy(str3, "copy successful");
	printf("str1: %s\nstr2: %s\nstr3: %s\n", str1, str2, str3);
	return 0;
}

insert image description here
In fact, we also found that strcpy still passed '\0', so strcpy has the following rules

  1. The source string must be terminated with '\0'.
  2. Will copy '\0' in the source string to the target space.
  3. The destination space must be large enough to hold the source string

We know the following rules, so let's create our own strcpy function

#include <assert.h>

//返回的是目标空间的起始地址
char* my_strcpy(char* dest, const char*src)
{
    
    
	char* ret = dest;
	assert(dest && src);
	while (*dest++ = *src++)
	{
    
    
		;
	}
	return ret;
}

int main()
{
    
    
	char arr1[] = "hehe";
	char arr2[20] = {
    
     0 };
	//my_strcpy(arr2, arr1);
	//printf("%s\n", arr2);
	printf("%s\n", my_strcpy(arr2, arr1));
	return 0;
}

By using it, it is different from the original function, and we know that this may be the source code of the strpy function.
After learning this, you actually find that these functions are actually simulated by programmers.

strcat function

Many people may have never seen this function, so I won’t say much about it. I put the original meaning in English.

Copies the first num characters of source to destination. If the end
of the source C string (which is signaled by a null-character) is
found before num characters have been copied, destination is padded
with zeros until a total of num characters have been written to it

The original intention is to add the contents of the array behind to the string behind

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

在这int main()
{
    
    
	char arr1[20] = "hello \0xxxxxxxxx";
	char arr2[] = "world";
	//追加
	strcat(arr1, arr2);
	printf("%s\n", arr1);

	return 0;
}

I also found that the result is hello world by running

The source string must be terminated with '\0'.
The destination space must be large enough to hold the contents of the source string.
target space must be modifiable

If you add it to yourself, add the code

int main()
{
    
    
	
	char arr2[] = "world";
	//追加
	strcat(arr2, arr2);
	printf("%s\n", arr2);

	return 0;
}

We will find that this code has been looping, and the picture I drew is below. According to the picture, you will find that '\0' is covered by the original.

insert image description here
Now that we know the rules, it becomes much easier to write a string of codes.
Make your own code:

#include<assert.h>
char* my_strcat(char* dest, const char*src)
{
    
    
	assert(dest && src);
	char* ret = dest;
	//找目标空间中的\0
	while (*dest != '\0')
	{
    
    
		dest++;
	}
	//拷贝
	while (*dest++ = *src++)
	{
    
    
		;
	}
	return ret;
}
int main()
{
    
    
	char arr1[20] = "bit";
	my_strcat(arr1, arr1);
	printf("%s\n", arr1);

	//char arr1[20] = "hello ";
	//char arr2[] = "world";
	//追加
	//my_strcat(arr1, arr2);
	//printf("%s\n", arr1);



	return 0;
}

This is the formation of the code, and the rules of strcat can be analyzed better through this code.

strcmp function

This function is composed of str+cmp, hey, we have to be alert, but we still have to guess whether it is a function that compares two arrays, then let's take a look

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.

We will find that this is a function that compares two arrays, let's test his rules with code

int main()
{
    
    
	//char* p = "abcdef";
	比较2个字符串的内容的时候,不能使用==,应该使用strcmp
	//if ("abcdef" == "bbcdef")//这里比较的是连个字符串首字符的地址,而并不是字符串的内容
	//{
    
    
	//}
	char arr1[] = "abq";
	char arr2[] = "abq";
	char arr3[] = "abc";
	char arr4[] = "abz";
	int ret = strcmp(arr1, arr2);
	int ret1 = strcmp(arr1, arr3);
	int ret2 = strcmp(arr1, arr4);

	printf("%d\n", ret);
	printf("%d\n", ret1);
	printf("%d\n", ret2);
	return 0;
}

insert image description here
So we find the following rules:

The standard stipulates:
if the first string is greater than the second string, return a number greater than 0. If
the first string is equal to the second string, return 0. If
the first string is less than the second string, return number less than 0

It is to compare letters one by one, skip if they are the same, until a character that is not the same ascII is compared, then stop, and the display will output the return value.
Knowing the rules, we simulate this function

#include <stdio.h>

int my_strcmp(const char* str1, const char* str2)
{
    
    
	assert(str1 && str2);
	while (*str1 == *str2) 
	{
    
    
		if (*str1 == '\0')
			return 0;
		str1++;
		str2++;
	}
	return *str1 - *str2;

	//if (*str1 > *str2)
	//	return 1;
	//else
	//	return -1;
}

int main()
{
    
    
	char arr1[] = "abzqw";
	char arr2[] = "abq";
	/*int ret = my_strcmp(arr1, arr2);
	printf("%d\n", ret);*/
	if (strcmp(arr1, arr2) >0)
		printf(">\n");
	return 0;
}

The comparison is made easier by comparing functions pointed to by pointers one by one. This is also the meaning of learning.

Summarize

Writing articles is actually relaxing for me. Facing tough exams, harrowing meetings, the stress of school.
Only by writing articles can you relax yourself, improve yourself, and let yourself have a better understanding, and I am a person who likes to share life and enjoy life, come to me if you have life troubles, come to me if you have stories, if you have wine, private messages must back.
Finally, I wish all the people who read my article a smooth business, no worries, and a happy journey down the road.

insert image description here
End with Lin Junjie's words: If you lose, you win the world, so what. Come on everybody

Guess you like

Origin blog.csdn.net/m0_73228832/article/details/129456503