当前位置:网站首页>(job) C language: Simulation Implementation of ATOI and strncpy, strncat, strncmp
(job) C language: Simulation Implementation of ATOI and strncpy, strncat, strncmp
2022-07-29 02:47:00 【dfnsyyds】
1. atoi() Realization
atio: Convert characters in a string to numbers
enum Status
{
VALID,
INVALID
}status = INVALID; // Create enumeration variable names status Its value is illegal Default illegal and easy
int my_atoi(const char* str)
{
int flag = 1;
// Null pointer
assert(str);
// An empty string
if (*str == '\0')
{
return 0;
}
// isspace Function to determine whether it is a space
while (isspace(*str))
{
str++;
}
// The sign
if (*str == '+')
{
flag = 1;
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
long long n = 0;
while (*str!='\0')
{
if (isdigit(*str))
{
// multiply flag, Make negative numbers add
n = n * 10 + flag * (*str - '0');
// n Judge after adding
if (n < INT_MIN || n > INT_MAX)
{
n = 0;
break;
}
}
else
{
break;
}
str++;
}
if (*str == '\0')
{
status = VALID;
}
return n;
}
int main()
{
// atoi A function that converts a string to an integer
char arr[20] = " -1234888";
int ret = my_atoi(arr);
if (status == VALID)
{
printf(" Normal conversion %d\n", ret);
}
else
{
printf(" Illegal conversion :%d\n", ret);
}
return 0;
}
The following are the implementation of string functions with limited length , belt n Indicates that an explicit copy is required 、 Additional 、 Length of comparison
2. strncpy:
strcpy(): String copy function
Learn how to use while(*dest++=*src++)
- Here is strcpy() The implementation of the
void my_strcpy(char* dest, const char* src)
{
// An error is reported when an error value is passed in
assert(dest && src);
// Even in the end \0, Also assign values first , After the copy is successful, the whole becomes 0, It will also make while stop
while (*dest++=*src++)
{
;}
}
The standard my_strcpy() The starting address of the target space will be returned , So start with char* res = dest; Again return res;
- strncpy(*dest, *src, int n) The implementation of the :
There are two situations :1. n Greater than src when ,2. n Less than or equal to src when :
- src Not enough , Then fill ’\0’;
- Less than or equal to full replication , Equal to ,dest Will be able to src Of ’\0’ Also fully copied . But less than , to src The next one becomes ‘\0’, Otherwise, it will leak .
void my_strcnpy(char* dest, char* src, int n)
{
assert(dest && src);
// Nothing here src length , as long as src There is , Just come in and do
while(*src)
{
while (*dest++ = *src++)
{
// When making conditions outside , It has been copied once .
n--;
// It's been copied n individual It's going to stop
if (n == 0)
{
*dest++ = '\0'; // prevent n Less than src length , At the end, there is no '\0';
break;
}
}
}
while (n>0)
{
*dest++ = '\0';
n--;
}
}
int main()
{
char s1[10] = "abba";
char s2[10] = "";
char s3[10] = "";
char s4[10] = "";
my_strcnpy(s2, s1, 4);
my_strcnpy(s3, s1, 2);
my_strcnpy(s4, s1, 8);
printf("%s\n", s1);
printf("%s\n", s2);
printf("%s\n", s3);
printf("%s\n", s4);
return 0;
}
s2、s3、s4: The corresponding length is exactly 、 Length shortage 、 The length is greater than the case , And the operation is normal

3.strncat: String append function with limited length
- strcat(): String append function
- hold src The string is appended to dest.
- seek dest Of ’\0’, This is the last . hold ’\0’ The starting value is changed to dest.
- There is no need to consider giving src Add... To the bottom ’\0’, Because copy one by one dest,dest Last bit yes ’\0’.
- And cmp Different first cycle to find dest last place .
void my_strncat(char* dest, char* src)
{
assert(dest && src); // dest and src To exist at the same time
// 1. Find the target first \0
while (*dest)
{
dest++;
}
while (*dest++ = *src++)
{
;
}
}
- strncat() The idea of : Restricted string append function
- Give the string s1 After adding s2 Of n individual .. There are two situations ,n Greater than s2,n Less than or equal to s2.
- n>len(s2), Then put s2 All plus , If s2 period , Make up the rest ’\0’;
- If n<len(s2), Then take n individual s2 value , to src
- n Less than s2 The length of the case , Additional n individual , Don't forget to give it to s1 Finally add ’\0’;
char* my_strncat(char* dest, char* src, int sz)
{
assert(dest && src); // dest and src To exist at the same time
// 1. Find the target first \0
char* res = dest;
while (*dest)
{
dest++;
}
// Now? dest yes \n sz Greater than src The length of
while (*src)
{
if (sz > 0)
{
*dest++ = *src++;
sz--;
}
else {
return res;
}
}
// src non-existent , But add sz individual , Just add it 0
if (sz == 0)
{
return res;
}
while (sz)
{
*dest++ = '\0';
sz--;
}
*dest++ = '\0';
return res;
}
int main()
{
// test my_strncat
char src[6] = "bbbbb";
char dest[25] = "aaaa";
printf(" The length is :%d\n", strlen(src));
my_strncat(dest, src, 5);
printf("111");
return 0;
}
Run the test :
Additional length n Greater than src Normal at length :

n Less than src It's normal :

3. be equal to src normal :

4. strncmp: String comparison function with limited length
- strcmp() The idea of :
- Comparing string sizes requires a bit by bit comparison , And there are only two situations for each : Currently wait or wait .
- Equality is more complicated : If you wait , See if one of them is ’\0’, If it is blank, return 0, Because it means that the two are always equal , Then move the pointer back and , Now it's at the end, or maybe it's just two empty strings at the beginning . If not now ’\0’, Just move the pointer back :s1++,s2++, Continue to compare the later .
- If the current bits are not equal , No circulation , Go straight back to *s1-*s2; Negative numbers indicate that the front is small , On the contrary, the front is big .
int my_strncmp(char* s1, char*s2)
{
assert(s1 && s2);
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return 0;
}
s1++;
s2++;
}
return *s1 - *s2;
}
- strncmp Ideas :
- stay strcmp On the basis of one more n The limitation of , That is to say n Within characters , Determine which of them is the size .
- As long as s1 and s2 The same part is limited , Because if it is less than n The place of , The two strings are different , It will come out while loop . No need to think about it. .
- Just pay attention to while When equal , Already compared n position , Just quit and explain n In characters , Two strings are equal .
- Running results :



边栏推荐
- Implement encapsulated public method global call in laravel framework
- owt-server源码剖析(四)--video模块分析之Mixer Out
- VR safety training of mine mining virtual reality improves employees' vigilance and protection awareness
- Workflow of wireless vibrating wire acquisition system
- 冰冰学习笔记:运算符重载---日期类的实现
- Memories of many years ago
- Really time NTP service startup command
- NVIDIA-VPI(Vision Programming Interface)
- 漫画算法_小灰灰面试
- Continuous learning / life long learning
猜你喜欢

Read the recent trends of okaleido tiger and tap the value and potential behind it

C语言:小乐乐与欧几里得

Asemi rectifier bridge s25vb100, s25vb100 parameters, s25vb100 application

Implement encapsulated public method global call in laravel framework

Three implementation methods of Servlet

FFmpeg+SDL+QT实现简单是视频播放器

Multimodal unsupervised image to image translation

A good-looking IAPP donation list source code

Workflow of wireless vibrating wire acquisition system

DHCP protocol detailed analysis
随机推荐
0728~ sorting out interview questions
Polygon zkevm - Introduction to HERMEZ 2.0
Mqtt routine
golang 协程的实现原理
Understand the evolution of redis architecture in one article
[untitled]
第五天实验
FPGA skimming memory (Verilog implementation of ram and FIFO)
C语言:判断字母
并发模式之异步回调Future模式
New UI Sifang aggregate payment system source code / new usdt withdrawal / latest update security upgrade to fix XSS vulnerability patch vulnerability
架构师进阶,微服务设计与治理的 16 条常用原则
Source code of Jiugongge heart puzzle Applet / source code of main wechat applet with traffic
What are the TCP retransmission mechanisms?
Source code and display of 18 classic programs in C language vs2019
一款好看的iapp捐赠榜单源码
Small program source code for campus stray cat information recording and sharing / wechat cloud development medium big cat spectrum small program source code
where、having、group by、order by,is null,not in,子查询,delete,日期函数
QT qstringlist usage
NVIDIA-VPI(Vision Programming Interface)