当前位置:网站首页>Detailed explanation of string operation functions and memory functions
Detailed explanation of string operation functions and memory functions
2022-06-25 13:10:00 【LIn_ jt】
strlen
First of all, the first male guest is our strlen function
Let's first look at the function prototype :>

strlen The argument to the function is the address of the required string , The return value is size_t type , Here we should pay attention to the following points :>
- strlen The return value of the function is size_t type , That is, the unsigned integer , The following happens :>

if In the sentence strlen(arr1) - strlen(arr2), namely 3 - 4 = -1, However, this is an unsigned integer - An expression of an unsigned integer , The result is still an unsigned integer ,-1 Will be treated as a large positive number , So the answer is > 了 
2.strlen There must be... In the requested string \0, strlen By reading \0 To stop reading , So if there is no end flag in the string , The result can only be a random value

The running result is :
Next is strlen Simulation Implementation of , There are three ways , What I write here is a pointer - The way of the pointer
int my_strlen(const char* start)
{
assert(start);
const char* end = start;
while (*end != '\0')
{
end++;
}
return end - start;
}
strcpy
The second male guest is our strcpy function , Its function is to copy one string to another , That's it :

take arr2 Copy to arr1 in , such arr1 Arrays are also stored arr2 The content in , The printed result is :>

The second thing to pay attention to is
1. There must be... In the copied source string \0, strcpy The same is true of \0 As the end of the copy .
2. When copying , Will also \0 Copy the past .
Let's show it through debugging
Now? , Let's change the string content of the first array , namely
char arr1[20] = "xxxxxxxxxxxxxxxxxxx";
char arr2[] = "hello, world!";
strcpy(arr1, arr2);
printf("%s\n", arr1);
after strcpy after

It can be seen that ,\0 Copied in the past .
Next is strcpy Simulation Implementation of :
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);
char* ret = dest;
while (*dest++ = *src++)
{
;
}
return ret;
}
*dest++ = *src++ This code solves the problem of copying , At the same time ’\0’ Copied the past .
strcmp
strcmp Is our commonly used string comparison function , Used to compare the size relationship between two strings
for example :>
int main()
{
char arr1[] = "LLLLLL";
char arr2[] = "LLLYYY";
int ret = strcmp(arr1, arr2);
printf("%d\n", ret);
return 0;
}
strcmp Compare each character in turn , Here, , arr1 Medium L Precede arr2 Medium L Compare , All the way to arr1 The fourth in L And arr2 The first of Y, The character... Is found at this time L Of ascii The code value is less than the character ’Y’, Returns a less than 0 Number of numbers , The result is :>
If we modify the code , If the arr2 The content in is modified to :>
int main()
{
char* arr1 = "LLLLLL";
char* arr2 = "LLLLLL";
int ret = strcmp(arr1, arr2);
printf("%d\n", ret);
return 0;
}
The result is :>

Next is strcmp Simulation Implementation of :>
int my_strcmp(const char* s1, const char* s2)
{
assert(s1 && s2);
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return 0;
}
s1++;
s2++;
}
return *s1 - *s2;
}
Here return *s1 - *s2 It can also be modified to the following code :>
if(*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
strcat
Next is our string append function , First , Its function is to append the string after the string , Use a string of code to demonstrate the following :>
int main()
{
char arr1[20] = "LLLLLL";
char arr2[] = "YYYYYY";
strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
The result is zero :>

The point to note is :>
- There must be enough space in the appended string function , Otherwise, it will cause illegal access to memory ;
- The appended string will also put ’\0’ Copy the past .
Then is strcat The simulation of
#include <assert.h>
char* my_strcat(char* dest, const char* src)
{
char* ret = dest;
assert(dest && src);
while (*dest)
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = "LLLLLL";
char arr2[] = "YYYYYY";
my_strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
The next three groups of functions are similar to the above three groups , Namely strncpy, strncmp, strncat.
First of all, our strncpy classmate , And strcpy One more parameter than

The third parameter here indicates how many characters to copy .
Next is its function demonstration :
int main()
{
char arr1[20] = "LLLLLLL";
char arr2[] = "YYYYYYYY";
strncpy(arr1, arr2, 3);
printf("%s\n", arr1);
return 0;
}
The result is zero :>

Let's change the code , Change to the following code :>
int main()
{
char arr1[] = "xxxxxxx";
char arr2[] = "YYY";
strncpy(arr1, arr2, 5);
printf("%s\n", arr1);
return 0;
}
The third parameter here ‘5’ Already exceeded arr2 The length of the string in ,arr1 The result obtained in is :>

You can see ,strncpy Not only the arr2 Copy the content from , Another one is added behind it ’\0’ In order to reach the five characters to be copied for the third parameter .
Next is myself to strncpy Simulation Implementation of , You are welcome to put forward your opinions !
char* my_strncpy(char* dest, const char* src, size_t count)
{
char* ret = dest;
while (count && (*dest++ = *src++)) // Here the expression (*dest++ = *src++) Must be on && Behind , When count by 0 when
{
// expression (*dest++ = *src++) Don't count , Prevent counting more than once
count--;
}
while (count)
{
*dest++ = '\0';
count--;
}
return ret;
}
And then there's our strncat, And strcat be similar , But there is also one more parameter

The third parameter also indicates that more numbers should be appended to the string . Next, let's look at its function
int main()
{
char arr1[20] = "xxxxxxx";
char arr2[] = "YYYYYYY";
strncat(arr1, arr2, 5);
printf("%s\n", arr1);
return 0;
}
The result is zero :>

It can be seen that ,strncat Not only five characters are appended , At the same time, it added ’\0’, If arr2 The length of the string in is less than the length specified by the third parameter , Look at the following code :>
int main()
{
char arr1[20] = "xx\0xxxxxxxxx";
char arr2[] = "YYY";
strncat(arr1, arr2, 5);
printf("%s\n", arr1);
return 0;
}
Let's take a debugging look at the results obtained after executing these lines of code :>

We found that , In the arr2 After appending all characters in the past , Even if arr2 The length of the string is less than strncat The parameter indicated by the third parameter , Still only arr2 The content in , It's not like strncpy Put a few more like that ’\0’ In the past .
Next is your own strncpy Simulation Implementation of , You are welcome to put forward your opinions !
char* my_strncat(char* s1, const char* s2, size_t count)
{
char* tmp = s1;
size_t len = strlen(s2);
while (*s1)
{
s1++;
}
if (count < len)
{
while (count && (*s1++ = *s2++))
{
count--;
}
*s1 = '\0';
}
else
{
while (len && (*s1++ = *s2++))
{
len--;
}
*s1 = '\0';
}
return tmp;
}
The last of these three sets of functions is our strncmp Function , First of all, the same is true , Since there is one more in the name n, Then he also has one more parameter .

First, let's look at its function :>

The third parameter here is to indicate that the first... In the two strings should be compared How many? Characters , What is passed here is 4, So contrast arr1 and arr2 The first four characters in , The result is zero :>

If the third parameter here is changed to 5 Words , And what you get is :>

because arr1 The fifth character of ’L’ And arr2 The fifth character in ’Y’ It's not equal , So it returns less than 0 Number of numbers .
Next is strncmp Own simulation implementation , You are welcome to put forward your opinions :>
int my_strcmp(const char* s1, const char* s2, size_t count)
{
assert(s1 && s2);
int i = 0;
for (i = 0; i < count; i++)
{
if (*s1 == *s2)
{
s1++;
s2++;
}
else
{
return *s1 - *s2;
}
}
return 0;
}
Next up is :
strstr
String lookup function , Find out whether a string is a substring of another string . If you find , Returns the address where the string was found , If can't find , Return null pointer . Look at the following example :>
int main()
{
char arr1[] = "abbbcdef";
char arr2[] = "bbc";
char* ret = strstr(arr1, arr2);
if (ret == NULL)
{
return 0;
}
else
{
printf("%s\n", ret);
}
return 0;
}
The result is zero :>

Next is strstr Simulation Implementation of (kmp I don't know the algorithm yet ....)
char* my_strstr(const char* str, const char* substr)
{
assert(str && substr);
if (*substr == '\0')
{
return (char*)str;
}
const char* s1 = str;
const char* s2 = substr;
const char* cur = str;
while (*cur)
{
s1 = cur;
s2 = substr;
while (*s1 && *s2 && (*s1 == *s2))
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)cur;
}
cur++;
}
return NULL;
}
Next is 4 Group memory function , Namely
memcpy;
memmove;
memset;
memcmp;
The first thing on the stage is memcpy, Let's look at its parameters 
The first parameter is the string to be copied , The second parameter is the copied string , The third is how many bytes are copied , Look at the following example :>
int main()
{
char arr1[] = "abcdef";
char arr2[10] = { 0 };
memcpy(arr2, arr1, 5);
printf("%s\n", arr2);
return 0;
}
The code here is to arr1 Copy the first five bytes to arr2 in . The result is zero :>
Besides ,memcpy Function can also operate on other types of arrays
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
memcpy(arr2, arr1, 5 * sizeof(arr1[0]));
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
The code here is to arr1 In front of 20 A byte element is copied to arr2 in , The result is zero :>

Next is memcpy The simulation of :>
void* my_memcpy(void* dest, const void* src, size_t count)
{
void* ret = dest;
while (count--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
Next on the stage is our memmove function , however memmove Function and memcpy Functions are very similar , but memmove Functions can handle overlapping problems .( Actually vs Of memcpy It's fine too ), Take a look at the code :>
void* my_memcpy(void* dest, const void* src, size_t count)
{
void* ret = dest;
while (count--)
{
*(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 };
my_memcpy(arr1 + 2, arr1, 4 * sizeof(arr1[0]));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
Here we want to put 1 2 3 4 copy to 3 4 5 6 The expected result is :1 2 1 2 3 4 7 8 9 10, However, we get the results for :>

here memmove It can solve the problem well , Let's change the code :>
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
memmove(arr1 + 2, arr1, 4 * sizeof(arr1[0]));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
The result is zero :>
memmove These overlapping problems can be solved , Next, let's focus on memmove Simulation Implementation of :>

First look at this picture , If you will 1,2,3,4 copy to 3,4,5,6 Will be covered 3,4 Words , We can try to copy it upside down , namely 
take 4 copy to 6, take 3 copy to 5, take 2 copy to 4, take 1 copy to 3, So we get the result we want .
Let's look at another situation

In this case, just copy it , the 3 copy to 1,4 copy to 2,5 copy to 3,6 copy to 4.
Last case :>

Both can be src perhaps dest, In this case , Just print backwards or directly , therefore , We can divide it into two situations

With this knowledge , Next is memmove Simulation Implementation of :>
void* my_memmove(void* dest, const void* src, size_t count)
{
void* tmp = dest;
assert(dest && src);
if (src > dest)
{
while (count--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
while (count--)
{
*((char*)dest + count) = *((char*)src + count);
}
}
return tmp;
}
memcmp
Next is the memory comparison function memcmp, That is to compare whether the contents of each byte are equal , And strcmp Quite similar 
Look at the following code
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
int arr2[] = {
1,2,3,4,6,7,8,9,10,11 };
int ret = memcmp(arr1, arr2, 16);
printf("%d\n", ret);
return 0;
}
The running result is :>

take 16 Change it to 17 Words , The result is zero :>
int main()
{
int arr1[] = {
1,2,3,4,5,6,7,8,9,10 };
int arr2[] = {
1,2,3,4,6,7,8,9,10,11 };
int ret = memcmp(arr1, arr2, 17);
printf("%d\n", ret);
return 0;
}

Back here -1 Because arr1 and arr2 pass the civil examinations 17 The contents of a byte are different , And arr1 The content in is less than arr2.
memset
The last one is our memset function , Memory setting function , Let's see the demonstration effect :>
int main()
{
char arr1[] = "LLLLLLLL";
memset(arr1, 'x', 5);
printf("%s\n", arr1);
return 0;
}
memset the arr1 Middle front 5 Bytes ( Here is 5 Bytes , Determined by the third parameter ) Set to ’x’ character x, The result is zero :>

The end of this paper !
边栏推荐
- Django framework - caching, signaling, cross site request forgery, cross domain issues, cookie session token
- Sword finger offer day 2 linked list (simple)
- .NET in China - What's New in .NET
- Heavyweight live | bizdevops: the way to break the technology situation under the tide of digital transformation
- 又是被Visdom搞崩溃的一夜
- 515. Find Largest Value in Each Tree Row
- 中国虚拟人哪家强?沙利文、IDC:小冰百度商汤位列第一梯队
- Alibaba stability fault emergency handling process
- Elemtnui select control combined with tree control to realize user-defined search method
- Jupyter Notebook主题字体设置及自动代码补全
猜你喜欢

Connect with the flight book and obtain the user information according to the userid

深圳民太安智能二面_秋招第一份offer

Uncover gaussdb (for redis): comprehensive comparison of CODIS

三行代码简单修改jar包的项目代码

Sword finger offer day 2 linked list (simple)

关于数据在内存中的存储下

J2EE from entry to earth 01 MySQL installation

Another night when visdom crashed

Configuring pytorch in win10 environment

Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"
随机推荐
New Gospel of drug design: Tencent, together with China University of science and technology and Zhejiang University, developed an adaptive graph learning method to predict molecular interactions and
MySQL 学习笔记
Resolved: could not find artifact XXX
Update PIP & Download jupyter Lab
Summer Ending
Possible problems when idea encounters errors occurred while compiling module (solved)
Command line garbled
torch.tensor拼接与list(tensors)
三行代码简单修改jar包的项目代码
Sword finger offer day 2 linked list (simple)
指针,它那些不得不说的题目
英语口语 - 弱读
《MongoDB入门教程》第01篇 MongoDB简介
You can't specify target table 'xxx' for update in from clause
First acquaintance with CANopen
MySQL writes user-defined functions and stored procedure syntax (a detailed case is attached, and the problem has been solved: errors are reported when running user-defined functions, and errors are r
药物设计新福音:腾讯联合中科大、浙大开发自适应图学习方法,预测分子相互作用及分子性质
Wechat full-text search technology optimization
.NET in China - What's New in .NET
LeetCode链表题解技巧归纳总结