当前位置:网站首页>Simulation of character function and string function
Simulation of character function and string function
2022-07-26 14:55:00 【ふり】
author :ふり
special column :C Advanced language
Maxim : Knowledge and practice go hand in hand
strlen Simulation Implementation of
1. Counter
#include <stdio.h>
#include <assert.h>
// Counter method
size_t my_strlen(const char *str)
{
assert(str);
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);
printf("%u\n",n);
return 0;
}
- strlen The return value of the function is size_t
- Define a new variable to calculate the string length
- const modification , The string will not be modified
- assert Assertion , What prevents passing is a null pointer
2. The pointer - The pointer
#include <stdio.h>
#include <assert.h>
// The pointer - The pointer
size_t my_strlen(const char* str)
{
assert(str);
char* ret = str;
while (*str != '\0')
{
str++;
}
return str - ret;
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);
printf("%u\n",n);
return 0;
}
The pointer - The pointer The result is the number of elements between two pointers , Record the address of the starting pointer , Look back with another pointer ‘\0’, Found subtraction , Get the string length
3. recursive
#include <stdio.h>
#include <assert.h>
// recursive
size_t my_strlen(const char* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
return 1 + my_strlen(str + 1);
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);
printf("%u\n",n);
return 0;
}
Recursion needs to find recursion conditions
strcpy Simulation Implementation of
#include <stdio.h>
#include <assert.h>
char* my_strcpy(char* dest, const char* str)
{
assert(dest && str);
char* ret = dest;
/*while (*str != '\0') { *dest = *str; str++; dest++; } *dest = '\0';*/
while (*dest++ = *str++)
{
;
}
return ret;
}
int main()
{
char arr1[] = "abcdef";
char arr2[20] = {
0 };
char* ret = my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
strcat Simulation Implementation of
#include <stdio.h>
#include <assert.h>
char* my_strcat(char* dest, const char* str)
{
char* ret = dest;
assert(dest && str);
while (*dest != '\0')
{
dest++;
}
while (*dest++ = *str++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = "Hello ";
char* ret = my_strcat(arr1, "world");
printf("%s\n", ret);
return 0;
}
When dest find ‘\0’, Then start adding what needs to be added step by step
strcmp Simulation Implementation of
#include <stdio.h>
#include <assert.h>
int my_strcmp(const char* str1, char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
return 0;
str1++;
str2++;
}
/*if (*str1 > *str2) { return 1; } else { return -1; }*/
return (*str1 - *str2);
}
int main()
{
char arr1[] = "hello";
char arr2[] = "world";
int ret = my_strcmp(arr1, arr2);
if (ret == 0)
{
printf("==\n");
}
else if (ret == 1)
{
printf(">\n");
}
else
{
printf("<\n");
}
return 0;
}
strstr Simulation Implementation of
#include <stdio.h>
#include <assert.h>
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
const char* s1 = str1;
const char* s2 = str2;
const char* p = str1;
while (*p!='\0')
{
s1 = p;
s2 = str2;
while (*s1!='\0'&& *s2 != '\0' &&* s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return p;
}
p++;
}
return NULL;
}
int main()
{
char email[] = "zgqqwertyuiop.com";
char substr[] = "qwertyuiop";
char* ret = my_strstr(email, substr);
if (ret == NULL)
{
printf(" The string does not exist \n");
}
else
{
printf("%s\n", ret);
}
return 0;
}
- First of all, our general idea is to start with the string str1 Find the string you want to find in str2 First element of , If you find it , Then compare the second element behind them , If the second element is the same and not ’\0’, Then continue to compare the third element , Keep comparing until the element being compared appears ’\0’, Now jump out of the loop , Judge this ’\0’ Does it belong to str2, If it belongs to , Then it meets the requirements , We directly return the first element address found at this time .
- If ’\0’ Belong to str1, Unqualified , We continued at the beginning str1 Search for str2 First element .
- If the first element is found str1 I still can't find it after the last character of , Then we return null pointer .
- In the process of concrete implementation , We introduce several intermediate variables ——s1、s2 and p, among s1 and s2 It is mainly used for synchronous dereference during the cycle to compare whether the characters at the corresponding positions of two strings are the same ,p Indicates the progress of finding the first element , Each entry into the cycle represents str1 There is a character that is used with str2[0] Compare once .
- In the process of concrete realization , We first create pointers of three character types , And give cp Fu Shang str1 Value , Then judge str2 Is it ‘\0’, if , Then we go straight back to str1 The address of ( Because it means str2 There is no valid element in , We go straight back str1 Value ).
- After excluding this situation , We go directly to the main cycle , The main cycle condition is cp, And after each cycle p++, We noticed that in p Move back to point to ’ \0 ’ The cycle condition is always true before the position of , Each element is cp When pointing, it will enter a cycle , Judge whether it is str2[0], Then look up the string backwards .
- After entering the cycle, we make s1 = p , s2 = str2 And use the following loop to find , Then follow our ideas step by step to achieve .
memcpy Simulation Implementation
#include <stdio.h>
#include <assert.h>
void* my_memcpy(void* dest,const void* str, size_t num)
{
assert(dest && str);
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)str;
dest = (char*)dest + 1;
str = (char*)str + 1;
}
return ret;
}
int main()
{
int arr1[10] = {
1,2,3,4,5,6,7,8,9,10 };
int arr2[5] = {
0 };
my_memcpy(arr2, arr1, 20);
for (int i = 0; i < 5; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}

memmove Simulation Implementation

hold 5 copy to 7 ,7 It becomes 5
hold 4 copy to 6 ,6 It becomes 4
hold 3 copy to 5 ,5 It becomes 3
hold 2 copy to 4 ,4 It becomes 2
hold 1 copy to 3 ,3 It becomes 1
Copy rules :

Code implementation :
#include <stdio.h>
#include <assert.h>
void* my_memmove(void* dest, const void* str, size_t num)
{
assert(dest && str);
char* ret = dest;
if (dest < str)
{
while (num--)
{
*(char*)dest = *(char*)str;
dest = (char*)dest + 1;
str = (char*)str + 1;
}
}
else
{
while (num--)
{
*((char*)dest + num) = *((char*)str + num);
}
}
return ret;
}
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr1 + 2, arr1, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
Conclusion
It is necessary for everyone to simulate and realize , Find out how the function is implemented
边栏推荐
- sqlDeveloper工具快速入门
- Wechat applet - "do you really understand the use of applet components?
- JS wave animation effect menu style
- Win11运行虚拟机死机了?Win11运行VMware虚拟机崩溃的解决方法
- Network pictures are transferred locally, causing the kernel to exit
- Fill in the questionnaire and receive the prize | we sincerely invite you to fill in the Google play academy activity survey questionnaire
- Leetcode summary
- CAS based SSO single point client configuration
- 14. Bridge-Based Active Domain Adaptation for Aspect Term Extraction 阅读笔记
- 基于CAS的SSO单点客户端配置
猜你喜欢

Summary of target tracking related knowledge

SiamRPN:建议区域网络与孪生网络

Unity learning notes – infinite map

Establishment of SSO single sign on environment based on CAS

median filter
![[dry goods] data structure and algorithm principle behind MySQL index](/img/80/d5ab431cd5112b1637ee07d5b59afa.png)
[dry goods] data structure and algorithm principle behind MySQL index

WPF 常用功能整合

How to evaluate the test quality?

Siamfc: full convolution twin network for target tracking

堆叠降噪自动编码器 Stacked Denoising Auto Encoder(SDAE)
随机推荐
Unity learning notes – infinite map
How to do app upgrade test?
How to get 5L water in a full 10L container, 7L or 4L empty container
31. Opinion-based Relational Pivoting forCross-domain Aspect Term Extraction 阅读笔记
Win11运行虚拟机死机了?Win11运行VMware虚拟机崩溃的解决方法
填问卷,领奖品 | 诚邀您填写 Google Play Academy 活动调研问卷
[Nuxt 3] (十二) 项目目录结构 1
Next generation visual transformer: Unlocking the correct combination of CNN and transformer
GOM login configuration free version generate graphic tutorial
WPF 常用功能整合
[draw with toolbar]
【1.2.投资的收益和风险】
【华为联机对战服务】客户端退出重连或中途进入游戏,新玩家如何补帧?
自编码器 AE(AutoEncoder)程序
[dry goods] data structure and algorithm principle behind MySQL index
Establishment of SSO single sign on environment based on CAS
Use of delve for go development and debugging
[solution of ordinary differential equation and drawing solution of small boat walking track]
php反序列化部分学习
Classic line style login interface
