Teach you how to use common string functions (including simulation implementation)

Table of contents

One, strlen

1. Know strlen

2. Use strlen

3. Expansion: Simulate the implementation of strlen

Two, strcpy

1. Know strcpy

2. Use strcpy

3. Expansion: Simulation implementation of strcpy

Three, strcmp

1. Know strcmp

2. Use strcmp

3. Expansion: Simulate the implementation of strcmp

Four, strcat

1. Know strcat

2. Use strcat

3. Expansion: Simulate the implementation of strcat

Five, strstr

1. Know strstr

2. Use strstr

3. Expansion: Simulate the implementation of strstr


One, strlen

1. Know strlen

Regarding the pictures of function definitions, this article is taken from cplusplus.com - The C++ Resources Network 

It can be seen from the return type of the function that the value returned by strlen is an unsigned integer , and then observed from the parameters, the character pointer variable is used, and the value of the address pointed to by const (constant) cannot be modified.

The purpose of strlen is also very simple, it is used to calculate the length of the string

2. Use strlen

#include<stdio.h>
#include<string.h>//声明函数,strlen被包含在这个头文件中
int main()
{
	char arr1[] = "abc def";//定义一个字符串
    int a=strlen(arr1);//返回的值是无符号整型,可以使用整型进行接收
	printf("%d\n",a);//将字符串长度打印出来验证
}

3. Expansion: Simulate the implementation of strlen

First of all, we have to clarify the goal of strlen , its goal is to calculate the length of the string , then the value we pass in the past should obviously be the address of the first character of the string, so that we can use the characteristics of the string (string \0) at the end to calculate the length of the string, the content pointed to by the passed pointer variable does not need to be modified, we only calculate the length. Therefore, the type of the value we pass in should be const char* . Then we judge the type returned by the function, the length of the string, obviously it should be an integer (no one has seen 0.1 characters) , so the type returned by our function should be int

I want to understand these problems, so let's talk about the implementation ideas next.

The idea is very simple, we know that the end of the string is \0, then we can traverse each character on the string, and then judge the termination condition according to /0, once encountering /0, the program will be terminated immediately.

upper code

#include<stdio.h>
#include<string.h>
int my_strlen(const char* a1)
{
	int count = 0;//计数器                     (\0的ASCII码值为0)
	while (*a1++)//当*a1,也就是此时a1对应的字符为'\0'时中止循环,遍历结束
	{
		count++;//每遍历一次就加1
	}
	return count;
}
int main()
{
	char arr1[] = "abc def";
	printf("%d\n",strlen(arr1));
	printf("%d\n", my_strlen(arr1));
}

Two, strcpy

1. Know strcpy

The return type of the strcpy function is char*, which is a character pointer, which is an address. The parameter type is two character pointers, and the content pointed to by the source character cannot be modified.

The purpose of strcpy is to overwrite the content of one string with the content of another string, note that it is an overwrite .

2. Use strcpy

#include<stdio.h>
#include<string.h>//strcpy位于此头文件中
int main()
{
	char arr1[] = "acdefg";
	char arr2[]= "abcd";
 	printf("%s\n", arr1);//打印被覆盖前的字符串
    strcpy(arr1, arr2);//arr1字符串被arr2字符串覆盖
	printf("%s\n", arr1);//打印被覆盖后的字符串
}

Why did I say coverage before, here I show you through the vs compiler

 Before going to strcpy, the content of arr1 and arr2 is, and then we go down the function of strcpy 

 

 It is not difficult to see that strcpy only realizes coverage, and does not completely change arr1 into arr2.

3. Expansion: Simulation implementation of strcpy

First of all, clarify the goal of strcpy. It is not difficult to see that a string is overwritten with another string.    The value of this function should pass two character addresses, but the details to pay attention to are that another character used to overwrite a string The characters on the string are only used, but not modified, but the covered string will obviously be modified. Therefore, the type of the covered string should be char* type , and the type of the overwritten string should be const char* type So   what return type should we use? In fact, void (empty type) can also be used, because our goal is to overwrite a string with another string,    but we'd better use the char* type to pass back an address to the main function, because in this way we can use the chain law.

I want to understand these problems, so let's talk about the implementation ideas next.

We know the first address of the two strings, then we can traverse both strings through '\0', we only need to traverse one string here, that is the string to implement the coverage, we We only need to overwrite this string on another string, and our task is completed. When it comes to this, some clever little friends will bypass the analogy. When the length of the string used to cover the string exceeds the covered string, won't it cross the boundary? Yes, it's out of bounds, such as this string of code

#include<stdio.h>
#include<string.h>
int main()
{
	char arr1[5] = "acde";
	char arr2[20]= "abcdeffff";
	printf("%s\n", strcpy(arr1, arr2));
}

The compiler will report an error, so the details that should be paid attention to when using this function is that the size of the overwritten string should be large enough.

The digression is over, let's go to the code

#include<stdio.h>
#include<string.h>
#include<assert.h>//assert的头文件
char* my_strcpy(char* str1, const char* str2)
{
assert(*str1 && *str2);
//断言一下,含义是当*str1或者*str2其中有一个是空字符串就报错,看不懂没关系,影响不大
char* ret = str1;
//储存被覆盖字符串的首地址,因为随着遍历,str1所指向的不再是之前的首地址
while(*str1++ = *str2++);
//遍历的同时进行覆盖,一旦覆盖到'\0'即为假,中止循环
return ret;
}
int main()
{
	char arr1[5] = "acde";
	char arr2[20]= "abcdeffff";
	printf("%s\n", arr2);
	printf("%s\n", arr1);
	printf("%s\n", my_strcpy(arr1, arr2));
}

Three, strcmp

1. Know strcmp

 The purpose of strcmp is to compare the size of two strings.   Its return type is integer , and there are two character pointer parameters. The content corresponding to these two addresses cannot be modified. The parameter type is const char* , which is worth one It is mentioned that when the string corresponding to str1 is greater than str2, the compiler returns a number greater than 0, which is equal to returning a number equal to 0, and less than returning a number less than 0, then strcmp uses which characteristic of the string to compare the size of the string What about? strcmp compares the characters on the string one by one, and returns the value according to the current comparison result if they are not equal. If it is always equal, compare until the end of '\0' and return 0

2. Use strcmp

#include<stdio.h>
#include<string.h>//strcmp函数位于这个头文件中
int main()
{
	char arr1[] = "eee";
	char arr2[] = "abcdGfg";
    int a=strcmp(arr1, arr2);//将比较的结果储存到a中
	printf("%d\n",a);//将结果打印出来
}

3. Expansion: Simulate the implementation of strcmp

In the old way, let’s look at the goal first. The goal is to compare the size of two strings. The way to achieve it is to take out the characters on the strings and compare them one by one. The return type of the function is obviously int, and the two parameters are not involved in modification, so both should be character pointers and the corresponding addresses cannot be modified, so the type should be const char*,

I want to understand these problems, so let's talk about the implementation ideas next.

Comparing the size of two strings is a one-to-one comparison of characters and then returning the value through the difference between the characters. Then we first need to traverse, by traversing the contents of the characters on the string until the two characters are not equal, then return the corresponding value. If it is always equal, compare until '\0' and return 0

upper code

#include<stdio.h>
#include<string.h>
#include<assert.h>
int my_strcmp1(const char* str1,const char* str2)
{
	assert(*str1 && *str2);
	while (*str1==*str2)//相等则一直遍历下去
	{
		if (*str1 == '\0')//遍历到'\0'停止
			return 0;
		str1++;
		str2++;
	}
	if (*str1 > *str2)
	{
		return 1;//大于返回大于0的数
	}
	else
		return -1;//小于返回小于0的数
}
int main()
{
	char arr1[] = "abcdefg";
	char arr2[] = "abcdGfg";
	printf("%d\n",strcmp(arr1, arr2));
	printf("%d\n", my_strcmp1(arr1, arr2));
}

Lite version

#include<stdio.h>
#include<string.h>
#include<assert.h>
int my_strcmp2(const char*str1,const char*str2)
{
	assert(*str1 && *str2);
	while (*str1==*str2)
	{
		if (*str1 == '\0')
			return 0;
		str1++;
		str2++;
	}
	return *str1 - *str2;//不相等时才会跳出循环,因此作差得所需值
}
int main()
{
	char arr1[] = "abcdefg";
	char arr2[] = "abcdGfg";
	printf("%d\n",strcmp(arr1, arr2));
	printf("%d\n", my_strcmp2(arr1, arr2));
}

Four, strcat

1. Know strcat

strcat is used to concatenate strings. It will copy the parameter source string to the end of the string pointed to by the parameter destination. The return type of the function is char*, and the two parameters are char* and const char*

2. Use strcat

#include<stdio.h>
#include<string.h>//strcat被包含在这个头文件中
int main()
{
	char arr1[20] = "acdefgh";
	char arr2[20] = "def";
	printf("%s",strcat(arr1, arr2));//打印拼接完成后的内容
}

3. Expansion: Simulate the implementation of strcat

In order to use the chain rule, we don't use the void type as the return value of the function here, although our work is just to splice two strings together. Parameter types, one is spliced ​​and can be modified, the other is used for splicing and does not need to be modified, so the parameter types are char* and const char*

I want to understand these problems, so let's talk about the implementation ideas next.

The key is to find the end of the spliced ​​string, which can be realized by '\0'. After the realization is completed, another string can be overwritten on the address at the end. It is still the same, and the spliced ​​string must be long enough. , otherwise it will cross the boundary.

upper code

#include<stdio.h>
#include<string.h>
char* my_strcat(char* str1, const char* str2)
{
	char* ret = str1;//储存开始时的地址,因为str1会再遍历时被改变
	while (*str1)//当*str1为'\0'时找到关键地址
	{
		str1++;
	}
	while (*str2)
	{
		*str1 = *str2;//开始覆盖
		str1++;
		str2++;
	}
	return ret;
}
int main()
{
	char arr1[20] = "acdefgh";
	char arr2[20] = "def";
	printf("%s",my_strcat(arr1, arr2));
}

Five, strstr

1. Know strstr

 The function of the strstr function is to find another string in a given string, and if it exists, return the position of the first occurrence . The return type of the function is const char*, and both parameters are const char*

2. Use strstr

#include<stdio.h>
#include<string.h>//strstr被包含在这个头文件中
int main()
{
	char arr1[] = "abcdefgbc";
	char arr2[] = "cde";
	printf("%s\n", strstr(arr1, arr2));//将查找到的地址所对应的字符串打印
}

3. Expansion: Simulate the implementation of strstr

The implementation idea of ​​this is more complicated, and the explanation is not clear in a few words. Let's directly upload the code and explain it through comments

#include<stdio.h>
#include<string.h>
#include<assert.h>
const char* my_strstr(const char*str1,const char*str2)
{
	while (*str1)//查找不到目标时也就是全部都找完了,来到了末尾'\0'中止循环
	{
		char* ch1 = str1;
      //假设现在就已经找到目标(因为每次遍历都可能找到目标),因此储存第一次出现的位置
		char* ch2 = str2;
     //目标字符串首元素的地址在每次查找前应重新取出,这样才能查找到对应字符串
		while (*ch2 == *ch1)//当此时地址对应的字符相等时进入循环
		{
			ch1++;
			ch2++;
			if (*ch2 == '\0')//因为被查找目标已经遍历完,因此中止循环
			{
				return str1;
			}
		}
		str1++;
	}
	return NULL;//找不到返回空指针
}
int main()
{
	char arr1[] = "abcdefgbc";
	char arr2[] = "cde";
	printf("%s\n", my_strstr(arr1, arr2));
}

Today's sharing is over here, thank you for your visit, I wish you a bright future O(∩_∩)O

Guess you like

Origin blog.csdn.net/fq157856469/article/details/131631744