Implement string functions and memory manipulation functions

Understanding the implementation process of library functions can help us use and understand them better. The following is the realization of string functions: strlen(), strcpy(), strcmp(), strstr(), memory functions: memcpy(), memmove()~

One, string function

1. Find the actual length of the string: strlen()

The library function is declared like this:

Code:

#include<stdio.h>
#include<windows.h>

size_t myStrlen(const char* str)
{
    //if语句校验合法性
	if (str == NULL){
		return 0;
	}
	size_t len = 0;
	while (str[len]!= '\0'){
		len++;
	}
	return len;
}
int main()
{
	char str[] = "hello world";
	printf("%d\n",myStrlen(str));
	system("pause");
	return 0;
}

operation result:

note:

①size_t represents unsigned integer

Variables modified by const generally cannot be changed. In order to prevent us from modifying the content of the string in the process of seeking the length of the string, we need to modify it with const to ensure that our string is safe and sound~

③Before calculating the length, it must be verified to verify the legality of the string .

2. String copy function: strcpy()

Declaration in the library function:

Code:

#include<stdio.h>
#include<windows.h>

char* myStrcpy(char* dest, const char* src)
{
    //if语句校验合法性
	if (dest == NULL || src == NULL){
		return NULL;
	}
	char* pdest = dest;
	const char* psrc = src;
	while (*psrc != '\0'){
		*pdest = *psrc;
		pdest++;
		psrc++;
	}
	*pdest = '\0';
	return dest;
}
int main()
{
	char dest[1024] = "hello";
	char src[] = "heihei";
	printf("%s\n", myStrcpy(dest, src));
	system("pause");
	return 0;
}

operation result:

It should be noted that in addition to the string legality check, because we are copying, we must ensure that the destination space is sufficient

3. String comparison function: strcmp()

Declaration in the library function:

Idea: If str1<str2, return a number less than 0, such as: -1

           If str1=str2 then return 0

           If str1>str2, return a number greater than 0, such as: 1

Code:

#include<stdio.h>
#include<windows.h>
#include<assert.h>

int myStrcmp(const char*str1, const char* str2)
{
    //assert检验字符串的合法性
	assert(str1!= NULL&&str2!=NULL);
	while (*str1 != '\0'&&*str2 != '\0'){
		if (*str1<*str2){
			return -1;
		}else if (*str1 > *str2){
			return 1;
		}else{
			str1++;
			str2++;
		}
	}
    //str1<str2,相减之后得到的是小于0的数
    //str1=str2,相减之后得到0
    //str1>str2,相减之后得到的是大于0的数
	return *str1 - *str2;
}
int main()
{
	const char str1[] = "helloapple";
	const char str2[] = "helloworld";
	printf("%d\n", myStrcmp(str1, str2));
	system("pause");
	return 0;
}

operation result:

Note: In addition to using the if statement to verify the validity, we can also use assert() . If the logic in the brackets is 0, then the program will be interrupted directly~ its header file is #include<assert.h>

4. The starting position function of the string search substring: strstr()

Declaration in the library function:

Ideas:

This function is a bit more complicated. It defines three pointers. The black pointer points to the first element of dest and traverses backwards in turn. If it is not found at the end of the traversal, it means that there is no substring matching src in dest. Define the red pointer, point to black, and define psrc to point to the first element of src. When we compare, if red and psrc are not equal, then the black pointer moves backward, our red points to black again, and psrc points to src again; if red If it is equal to psrc, then continue to use red to compare whether it is equal to the remaining characters in src, until src has been traversed, then it means that it has been found, and return to the position pointed to by black.

Code:

#include<stdio.h>
#include<windows.h>

char* myStrstr(const char* dest, const char* src)
{
    //if语句校验合法性
	if (dest == NULL || src == NULL){
		return NULL;
	}
	const char* black= dest;
	while (*black != '\0'){
		const char* red = black;
		const char* psrc = src;
		while (*red == *psrc && *red != '\0' && *psrc != '\0'){
			red++;
			psrc++;
		}
		if (*psrc == '\0'){
			return black;
		}
		black++;
	}
	return NULL;
}
int main()
{
	char dest[] = "helloworld";
	printf("%s\n", myStrstr(dest, "ow"));
	system("pause");
	return 0;
}

operation result:

Pay attention to the legality of verification~

Two, memory operation function

1. Memory copy function: memcpy()

Declaration in the library function:

When writing the memory copy function, I came up with a very silly question, isn’t there a string copy, why do I need this, and then I quickly realized that the string function copy is only for strings, but memory copy The return value of the function is void*, which means that it can copy any type of data! ! In order to be able to copy any type, we need to copy byte by byte. The char type occupies just 1 byte, so in the function, we force (void *) to be (char*) type, and size_t num is ours The number of bytes to be copied.

Code:

#include<stdio.h>
#include<windows.h>
#include<assert.h>

void* myMemcpy(void* dest, const void* src,size_t num)
{
    //assert校验合法性
	assert(dest!= NULL&&src!=NULL);
	char* pdest = (char*)dest;
	const char* psrc = (char*)src;
	for (size_t i = 0; i < num; i++){
		*(pdest+i) = *(psrc+i);
	}
	return dest;
}
int main()
{
	int dest1[4] = {1,0,2,4};
	const int src1[4] = { 6, 6, 6, 6 };
	char dest2[1024] = "hei";
	const char src2[1024] = "helloworld";
	for (int i = 0; i < (sizeof(dest1) / sizeof(dest1[0])); i++){
		printf("%d", dest1[i]);
	}
	printf("\n%s\n", myMemcpy(dest2, src2, sizeof(src2)));
	system("pause");
	return 0;
}

operation result:

Pay attention to the legality of verification~~

2. Memory copy function: memmove()

Declaration in the library function:

And memcpy difference is a function of process memmove source memory blocks and the target memory block is to be overlapped . If the source space and target space overlap, you have to use the memmove function.

If the target memory block is in the source memory block, then it is necessary to reverse copy (reverse copy is to copy the last position in the source to the last position in the destination, copy from back to front in turn, if you don’t know why, you can Make a gesture on the paper), on the contrary, just execute the above memcpy normally~

Code:

#include<stdio.h>
#include<windows.h>
#include<assert.h>

void* myMemcpy(void* dest, const void* src,size_t num)
{
	assert(dest!= NULL&&src!=NULL);
	char* pdest = (char*)dest;
	const char* psrc = (char*)src;
	for (size_t i = 0; i < num; i++){
		*(pdest+i) = *(psrc+i);
	}
	return dest;
}

void* myMemmove(void* dest, const void* src, size_t num)
{
	assert(dest != NULL&&src != NULL);
	char* pdest = (char*)dest;
	const char* psrc = (char*)src;
	if (pdest>=psrc&&pdest<=psrc){
		for (size_t i =num-1; i >= 0; i--){
			*(pdest + i) = *(psrc + i);
		}
		return dest;
	}
	return myMemcpy(dest, src, num);
}
int main()
{
	char str[] = "hello world ni hao shi jie..";
	printf("%s\n", myMemmove(str+11,str+12,18));
	system("pause");
	return 0;
}

operation result:

Pay attention to the legality of verification~~~

 

bye~~~~~~

 

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/110014263