当前位置:网站首页>Simulation Implementation of string function (Part 1)
Simulation Implementation of string function (Part 1)
2022-07-25 02:33:00 【Four years later.】
List of articles
strlen function
size_t strlen ( const char * str );
strlen The return value of the function is size_t
What is? size_t ?
size_t: typedef unsigned int size_t ( stay 32 Bit operating system )
That is to say unsigned int
strlen Use of functions
int main()
{
char arr1[] = "hello world";
int len = strlen(arr1);
printf("%d\n", len);
return 0;
}
Simulation Implementation strlen
// The method of counting
int my_strlen(char* str)
{
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
// Method of subtracting pointer from pointer
int my_strlen(char* str)
{
char* tmp = str;
while (*tmp != '\0')
{
tmp++;
}
return tmp - str;
}
// Recursive method
int my_strlen(char* str)
{
// Termination conditions
if (*str == '\0')
{
return 0;
}
return 1 + my_strlen(str + 1);
}
1、strlen The function returns a string with ‘\0’ The number of characters that appear before , barring ‘\0’
But in sizeof In keywords Will be able to ‘\0’ As the size of the occupied space sizeof Just look at the size of the space
2、( It's easy to get wrong ) The return value of the function is an unsigned integer
3、 If the string does not start with ‘\0’ At the end of the day ,strlen The value returned by the function is a random value
strcpy function
char * strcpy ( char * destination, const char * source );
from source Copy the source address to destination In the address
1、 The target space has to be large enough , It can accommodate the source string
2、 The target space has to be variable
3、 copy to ‘\0’ When , Copy Stop
xxxxxxxx zhang \0 san
At the time of copying , Memory will store zhang \0 xxx
This proves the above view
4、 The source data should be guaranteed to have ‘\0’
strcpy Use of functions
int main()
{
char arr1[] = "hello world";
char arr2[20] = {
0 };
strcpy(arr2, arr1);
puts(arr2);
return 0;
}
Simulation Implementation strcpy
#include<assert.h>
char* my_strcpy(char* str1,char* str2)
{
assert(str1 && str2);
while (*str1++ = *str2++)
{
;
}
return str1;
}
int main()
{
char arr1[20] = {
0 };
char arr2[] = "abcdef";
my_strcpy(arr1, arr2);
puts(arr1);
return 0;
}
strcat function
char * strcat ( char * destination, const char * source );
1、 The target space has to be large enough , It can accommodate the contents of the source string
2、 The target space must be modifiable
3、 The source string must be ‘\0’ end
strcat Use of functions
Simulation Implementation strcat
#include<assert.h>
char* my_strcat(char* str1, char* str2)
{
assert(str1 && str2);
while (*str1 != '\0')
{
str1++;
}
while (*str1++ = *str2++)
{
;
}
return str1;
}
int main()
{
char arr1[30] ="hello world";
char arr2[] = "abcdefghi";
my_strcat(arr1, arr2);
puts(arr1);
return 0;
}
strcmp function
int strcmp ( const char * str1, const char * str2 )
To compare two strings strcmp function

The first string is larger than the second string , Return greater than 0 The number of
The first string is equal to the second string , Then return to 0
The first string, little fish, the second string , Then return less than 0 The number of
strcmp Use of functions
int main()
{
char arr1[] = "abcdef";
char arr2[] = "abcq";
int ret = strcmp(arr1, arr2);
if (ret > 0)
{
printf(">\n");
}
else if (ret == 0)
{
printf("==\n");
}
else
printf("<\n");
return 0;
}
Simulation Implementation strcmp
#include<assert.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;
}
int main()
{
char arr1[] = "abc";
char arr2[] = "abc";
int ret = my_strcmp(arr1, arr2);
if (ret > 0)
{
printf(">\n");
}
else if (ret == 0)
{
printf("==\n");
}
else
printf("<\n");
return 0;
}
memcpy function
void * memcpy ( void * destination, const void * source, size_t num )
1、memcpy Function encountered ‘\0’ When It won't stop
2、 Function from source The position of begins to be copied back num Bytes of data to destnation The location of
memcpy Use of functions
#include<stdio.h>
#include<string.h>
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
int arr2[20] = {
0 };
memcpy(arr2, arr1, 40);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
Simulation Implementation memcpy
1、 When simulating the implementation , Parameter type void* , Because I don't know the specific data type , It is more reasonable to design generic pointers
2、 Return the starting address of the target space
3、num Determines the number of bytes copied
#include<stdio.h>
#include<string.h>
#include<assert.h>
void* my_memcpy(void* dest, const void* src, size_t num)
{
assert(dest && src);
// because dest To change the Save the starting address to return
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
int arr2[20] = {
0 };
my_memcpy(arr2, arr1, 40);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
memmove function
void * memmove ( void * destination, const void * source, size_t num )
memmove Functions and memcpy The parameters of the function are exactly the same
memmove Functions and memcpy Function comparison
If there is memory overlap, you need to use memmove memcpy Although functions can also be implemented memmove The function of , however C The language standard stipulates that when encountering memory overlap memmove function
memmove Use of functions
// hold arr1 in from 1 At the beginning 20 The contents of bytes are copied to from 3 Start on memory
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
memmove(arr1+2, arr1, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
Simulation Implementation memmove
When dest stay src In front of : There is a situation

When dest stay src In the back : There are two situations


In the array , The address changes from low to high
When src The address of is less than dest The address of , That is to say src stay dest In front of , Copy from back to front
When src The address of is greater than dest The address of , That is to say src stay dest At the back of , Copy from front to back

void* my_memmove(void* dest, const void* src, size_t num)
{
assert(dest && src);
// because dest To change the Save the starting address to return
void* ret = dest;
if (dest < src)
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
while (num--)
{
*((char*)dest + num) = *((char*)src + num);
}
}
return ret;
}
// hold arr1 in from 1 At the beginning 20 The contents of bytes are copied to from 3 Start on memory
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
memmove(arr1+2, arr1, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
memcmp function
int memcmp ( const void * ptr1, const void * ptr2, size_t num
Compare from ptr1 and ptr2 The pointer starts with num Bytes
memcmp Use of functions
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[] = "hello";
char arr2[] = "abcde";
int ret = memcmp(arr1, arr2, 20);
if (ret > 0)
{
printf(">\n");
}
else if (ret == 0)
{
printf("==\n");
}
else
printf("<\n");
return 0;
}
边栏推荐
- Can PostgreSQL CDC only connect to the main database? Connection from the library reports an error logical decoden
- Scalar, vector, matrix calculus
- Automatically create partition tables by time and month in PostgreSQL
- Keepalivetime=0 description of ThreadPoolExecutor
- Why can't reading more books improve your writing?
- Cloud native platform, let edge applications play out!
- C language: Structure -- a detailed explanation of memory byte alignment
- How to upload files to the server
- "Introduction to interface testing" punch in to learn day09: Micro service interface: how to use mock to solve chaotic call relationships
- Sword finger offer 11. rotate the minimum number of the array
猜你喜欢

Simulate the implementation of StrCmp function

Generator set work arrangement problem code

Hongmeng harmonyos 3 official announcement: officially released on July 27; Apple slowed down the recruitment and expenditure of some teams in 2023; Russia fined Google 2.6 billion yuan | geek headlin

Win10 configuring CUDA and cudnn

Genesis, the world's first "consumption investment" public chain, was invited to participate in consensus 2022

Nacos service discovery data model

Picgo configuring Alibaba cloud OSS

July 8, 2022

Explanation of C language file operation function

Redis unauthorized access vulnerability recurrence (www.hetianlab.com)
随机推荐
Easy to master SSO single sign on, see this article
What are the basic skills of engineers? How to practice? -- Learning experience sharing "suggestions collection"
"Introduction to interface testing" punch in day06: interface testing platform: are tools and frameworks incompatible?
Picgo configuring Alibaba cloud OSS
A bit of knowledge - websites about scripts
Seven text editors that programmers should know are necessary for programming
xts performance auto fix script
Generator set work arrangement problem code
Mgre.hdlc.ppp.chap.nat comprehensive experiment
Is it necessary to increase the number of milliseconds and save several KB of memory in the program?
Coal industry supply chain centralized mining system: digitalization to promote the transformation and upgrading of coal industry
Use Fiddler to capture apps
Redux best practices "Redux toolkit"
Flutter apple native Pinyin keyboard input exception on textfield | Pinyin input process callback problem
Please ask a question: how to set the new table of MySQL CDC 2.2.x to only receive increment
Go language path is relative, but relative Import paths are not supported in module mode
What do growth enterprises need most to build a data-driven organization?
Android memory optimized disk cache
On the economic model of open source ecology
Digital commerce cloud fine chemical industry management platform integrated informatization solution