当前位置:网站首页>Analog library function
Analog library function
2022-07-27 09:16:00 【Blue cat Knight】
1.strlen Three methods of simulation
Strlen Command to get the specified key The length of the stored string value . When key When a string value is not stored , Return an error .
#include<stdio.h>
#include<assert.h>
// How to count
int my_strlen(const char* str)
{
assert(str != NULL); // Assertion Prevent dereference null pointer from reporting errors
int count = 0;
while (*str)
{
count++;
str++;
}
return count;
}
// Recursive method
int my_strlen(const char * str)
{
if(*str == '\0')
return 0;
else
return 1+my_strlen(str+1);
}
// The pointer - The way of the pointer
int my_strlen(char *s)
{
char *p = s; // p Get is s The first address
while(*p != ‘\0’ )
p++;
return p-s;
}
int main()
{
char str[] = "abcdefg";
int len = my_strlen(str);
printf("%d", len);
return 0;
}
//assert() Is a macro that is often used when debugging programs ,
// When the program is running, it evaluates the expression in brackets ,
// If the expression is false(0), The program will report an error , And terminate execution .
// If the expression is not 0, Then continue to execute the following statements .
// This macro usually determines whether there is obviously illegal data in the original program ,
// If there is a termination procedure, so as not to cause serious consequences , At the same time, it is also easy to find errors .
//
//assert Only in Debug Only valid in version , If compiled as Release Version is ignored .
//** So when If we pass a null pointer , Then the program will go wrong , We need to avoid that 2. strcpy char *strcpy(char *dest, const char *src)
hold src The string you point to is copied to dest.
Note that if the target array dest Not big enough , And the length of the source string is too long , It may cause buffer overflow .
char *my_strcpy(char *dest, const char*src)
{
char *ret = dest;
assert(dest != NULL);
assert(src != NULL);
while((*dest++ = *src++))
{
;
}
return ret; // Returns a string that points to the final destination dest The pointer to
}
int main()
{
char arr1[10] = "xxxxx";
char arr2[] = "hello";
my_strcpy(arr1, arr2);
printf("%s", arr1);
return 0;
}3.strcat
char *strcat(char *dest, const char *src)
hold src The string pointed to is appended to dest The end of the string that you are pointing to .
my_strcat(arr1, arr1); I can't add it to myself There will be bug it is to be noted that
char *my_strcat(char *dest, const char*src)
{
char *ret = dest;
assert(dest != NULL);
assert(src != NULL);
while(*dest) // Use the loop to dest + To \0
{
dest++;
}
while((*dest++ = *src++))
{
;
}
return ret;
}
int main()
{
char arr1[20] = "xxxxx";
char arr2[] = "hello";
my_strcat(arr1, arr2);
printf("%s", arr1);
return 0;
}4.strcmp Compare two strings for equality
The picture on the right is captured on the website of rookie tutorial ( The website address is placed at the end of the article ) , You can see it directly strcmp The return value of the function There are three kinds of = 0 > 0 < 0 therefore When we simulate, we need to bring the return type int Use return value 0 ,1 ,-1. To judge
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2); // Prevent dereference Report errors
while (*str1 == *str2)
{
if (*str1 == '\0')
return 0;
str1++;
str2++;
}
if (*str1 > *str2)
{
return 1;
}
else
{
return -1;
}
// simplify
assert(str1 && str2); // Prevent dereference Report errors
while (*str1 == *str2)
{
if (*str1 == '\0')
return 0;
str1++;
str2++;
}
return *str1 - *str2;
}
int main()
{
char arr1[20] = "zhangsaa";
char arr2[] = "zhangsanfeng";
// Compare two strings for equality
//strcmp
int ret = my_strcmp(arr1, arr2); // The essence here is to compare ASCII code
if (ret < 0)
{
printf("<\n");
}
else if (ret > 0)
{
printf(">\n");
}
else
{
printf("==\n");
}
}5.strstr A function to find a substring
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
char *cp = (char*) str1; // utilize cp Record str1 Location information for
char *s1, *s2;
if (!*str2)// And *s2 == '\0' Equivalent
return((char*)str1);
while (*cp)
{
s1 = cp;
s2 = (char*) str2;
while (*s1 && *s2 && !(*s1-*s2))// Cycle until s1 s2 End or s1 != s2
s1++, s2++;
if (!*s2)//
return(cp);
cp++;
}
return(NULL);
}
int main()
{
char email[] = "[email protected]";
char substr[] = "qq";
char* ret = my_strstr(email, substr);
if (ret == NULL)
{
printf(" non-existent \n");
}
else
{
printf("%s\n",ret);
}
}6.memcpy
void *memcpy(void *str1, const void *str2, size_t n)
From the storage area str2 Copy n Bytes to storage str1
void* my_memcpy(void* dest, const void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)src; // utilize char* It is a more appropriate method to skip byte by byte
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
char arr1[10] = "xxxxx";
char arr2[] = "hello";
my_memcpy(arr1, arr2,2);
printf("%s", arr1);
int arr1[] = { 1,2,3,4,5,6,7 };
int arr2[10] = { 0 };
my_memcpy(arr2+1, arr1, 24); // 4*7
float arr3[5] = { 1.2,1.4 ,1.0,1.3,1.7 };
float arr4[10] = { 0.0 };
my_memcpy(arr4, arr3, 20); // 4*5
return 0;
}7.memmove
void *memmove(void *str1, const void *str2, size_t n)
from str2 Copy n Characters to str1,
But in terms of overlapping memory blocks ,memmove() It's better than memcpy() A safer way . If the target region and the source region overlap ,memmove() It can ensure that the bytes of the overlapping area are copied to the target area before the source string is overwritten , After copying, the contents of the source area will be changed . If the target region does not overlap with the source region , And memcpy() Same function .
namely You can copy yourself
memcpy Be responsible for copying data in two independent spaces
Copy of overlapping memory Yes, it is memmove
void* my_memmove(void* dest, const void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
// Copy in both directions Consider from front to back
if (dest < src)
{
// front —> after
while (num--)
{
*(char*)dest = *(char*)src; // utilize char* It is a more appropriate method to skip byte by byte
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else // after --> front
{
while (num--)// num It is reduced every time here
{
*((char*)dest + num) = *((char*)src + num); // + num Copy from back to front
}
}
return 0;
}
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7 };
memmove(arr1 + 1, arr1+2, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
}边栏推荐
- ArkUI框架中的两个小技巧
- [leetcode -- the second day of introduction to programming ability] operator (the number of bit 1 / the difference between the sum of the products of integers)
- 基于ArkUI eTS开发的坚果食谱(NutRecipes
- PVT的spatial reduction attention(SRA)
- JS call and apply
- ES6 new - Operator extension
- Babbitt | yuan universe daily must read: Guangzhou Nansha released the "Yuan universe nine" measures, and the platform can obtain up to 200million yuan of financial support
- CUDA programming-01: build CUDA Programming Environment
- Common operations of BOM and compatible writing methods for obtaining page / window height, width and scrolling
- STL container - basic operation of queue and deque
猜你喜欢

npm install报错 强制安装

5G没能拉动行业发展,不仅运营商失望了,手机企业也失望了

Specific methods and steps for Rockwell AB PLC to establish communication with PLC through rslinx classic
![[C language _ study _ exam _ review lesson 3] overview of ASCII code and C language](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[C language _ study _ exam _ review lesson 3] overview of ASCII code and C language

500 error reporting

pollFirst(),pollLast(),peekFirst(),peekLast()

ctfshow 终极考核

Linux Installation and remote connection MySQL records

音乐体验天花板!14个网易云音乐的情感化设计细节

Longest string without duplicate characters
随机推荐
HUAWEI 机试题:火星文计算 js
PVT的spatial reduction attention(SRA)
New year's goals! The code is more standardized!
How to optimize the deep learning model to improve the reasoning speed
How to upload dynamic GIF map in blog
As a VC, the auction house invested Web3 for the first time
[cloud native kubernetes practice] deploy the rainbow platform under the kubernetes cluster
5G没能拉动行业发展,不仅运营商失望了,手机企业也失望了
Apple cut its price by 600 yuan, which was almost a devastating blow to the collapse of its domestic flagship mobile phone
对 int 变量赋值的操作是原子的吗?
博客怎么上传动态gif图
【每日算法Day 96】腾讯面试题:合并两个有序数组
Svg drawing curve
linux安装和远程连接mysql记录
Music experience ceiling! Emotional design details of 14 Netease cloud music
软件测试功能测试全套常见面试题【功能测试-零基础】必备4-1
[daily algorithm day 96] Tencent interview question: merge two ordered arrays
npm install报错 强制安装
Tensorflow package tf.keras module construction and training deep learning model
被三星和台积电挤压的Intel终放下身段,为中国芯片定制芯片工艺