当前位置:网站首页>String & memory function (detailed explanation)
String & memory function (detailed explanation)
2022-07-04 01:45:00 【Xiao Mofan】
Catalog
One 、 Unlimited length string function
Two 、 String function with limited length
3、 ... and 、 Other string functions
Four 、 Memory manipulation function
5、 ... and 、 Simulation and implementation of library functions
1. Simulation Implementation strlen function
2. Simulation Implementation strcpy function
3. Simulation Implementation strcat function
4. Simulation Implementation strcmp function
5. Simulation Implementation strncpy function
6. Simulation Implementation strncat function
7. Simulation Implementation strncmp function
8. Simulation Implementation strstr function
9. Simulation Implementation memcpy function
10. Simulation Implementation memmove function
11. Simulation Implementation memcmp function
12. Simulation Implementation memset function
One 、 Unlimited length string function
1.strlen function
String to ‘\0’ As an end sign ,strlen The function returns the number of characters that appear in front of the string
The function prototype :size_t strlen( const char *string );
head writing Pieces of :<string.h>
The functionality : Calculate the length of the string ;
matters needing attention :1. The defined string must contain '\0'
char arr1[] = "abcd";/* correct */ char arr2[] = { 'a', 'b', 'c', 'd' };/* error */
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "ABCD";// It contains \0
char str2[] = { 'A','B','C','D' };// It doesn't contain \0
printf("%d\n", strlen(str1));
printf("%d\n", strlen(str2));
return 0;
}
2.strcpy function
The function prototype :char *strcpy( char *strDestination, const char *strSource );
head writing Pieces of :<string.h>
The functionality : String copy ; It is together with '\0' Copy it together ;
Parameter interpretation :
1.char *strDestination --- Target string
2.const char *strSource --- The source string ( Cannot be modified )
3. Return type :char* --- What is returned is the address of the source string after copying
matters needing attention :
1. When copying, the source string must contain \0;
2. When copying, the target space should be large enough , Make sure to copy the past string ;
3. The target space must be modifiable when copying ( Can not be const modification );
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "xxxxxxx";// The target space should be large enough
char str2[] = "Hello World";
printf(" Before copying :%s\n", str1);
strcpy(str1, str2);
printf(" After copying, it is :%s\n", str1);
return 0;
}
3.strcat function
The function prototype :char *strcat( char *strDestination, const char *strSource );
head writing Pieces of :<string.h>
The functionality : String connection ( Additional ): It is together with '\0' Add the past together ;
Parameter interpretation :
1.char *strDestination --- Target string
2.const char *strSource --- The source string ( Cannot be modified )
3. Return type :char* --- What is returned is the address of the source string after copying
matters needing attention :
1. When appending, the source string must contain \0
2. When appending, the target space should be large enough , Make sure to append the past string
3. When appending, the target space must be modifiable ( Can not be const modification )
4. I can't add to myself ( Need to use strncat)
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello ";// The target space should be large enough
char str2[] = "World";
printf(" Before addition is :%s\n", str1);
strcat(str1, str2);
printf(" After addition is :%s\n", str1);
return 0;
}
4.strcmp function
The function prototype :int strcmp( const char *string1, const char *string2 );
head writing Pieces of :<string.h>
The functionality : String comparison : The comparison is ASSIC Code value ; Content is compared, not length ;
Parameter interpretation :
1.string1 --- The string being compared ;
2.string2 --- String to be compared ;
Comparison method :
1. When str1 < str2 Return negative
2. When str1 = str2 return 0
3. When str1 > str2 Return positive number
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "ABCD";
char str2[] = "ABCE";
int ret = strcmp(str1, str2);
if (ret > 0)
{
printf("ret=%d:str1>str2\n", ret);
}
else if (ret < 0)
{
printf("ret=%d:str1<str2\n", ret);
}
else
{
printf("ret=%d:str1=str2\n", ret);
}
return 0;
}
Two 、 String function with limited length
1.strncpy function
The function prototype :char *strncpy( char *strDest, const char *strSource, size_t count );
head writing Pieces of :<string.h>
The functionality : String copy : Sure Appoint Number of copied characters ;
Parameter interpretation :
1.char *strDest --- Target string
2.const char *strSource --- The source string ( Cannot be modified )
3.size_t count --- Specify how many characters to copy
4. Return type :char* --- What is returned is the address of the source string after copying
matters needing attention :
1. When copying : When the number of copies is greater than the length of the source string ( Such as source string “abcd”, Copy 6 individual ), Not enough \0 repair ( Set the number reasonably )
2. When copying, the target space should be large enough , Make sure to copy the past string
3. Target space when copying Must be modifiable ( Can not be const modification )
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char dest[20] = "xxxxxxx";
char src[] = "Hello World";
printf(" Before copying :%s\n", dest);
strncpy(dest, src,5);
printf(" After copying, it is :%s\n", dest);
return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
char dest[20] = "xxxxxxxxxx";
char src[] = "abcd";
printf(" Before copying :%s\n", dest);
strncpy(dest, src, 6);
printf(" After copying, it is :%s\n", dest);
return 0;
}
2.strncat function
The function prototype :char *strncat( char *strDest, const char *strSource, size_t count );
head writing Pieces of :<string.h>
The functionality : String append : Sure Appoint Number of additional characters ;
Parameter interpretation :
1.char *strDest --- Target string
2.const char *strSource --- The source string ( Cannot be modified )
3.size_t count --- Appoint Additional How many characters
4. Return type :char* --- What is returned is the address of the source string after copying
matters needing attention :
1. When appending : When the number of appendixes is less than the number of source strings , Will actively add '\0'
2. When appending : When the number of appendixes is greater than the number of source strings , The definition of library function is to append to '\0' Location , So even if the number is large, it doesn't affect
3. When appending, the target space must be modifiable ( Can not be const modification )
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char dest[20] = "Hello ";
char src[] = "World";
printf(" Before addition is :%s\n", dest);
strncat(dest, src, 4);
printf(" After addition is :%s\n", dest);
return 0;
}
3.strncmp function
The function prototype :int strncmp( const char *string1, const char *string2, size_t count );
head writing Pieces of :<string.h>
The functionality : String comparison : Sure Appoint Compare the number of characters ;
Parameter interpretation :
1.string1 --- The string being compared ;
2.string2 --- String to be compared ;
3.size_t count --- Appoint Compare How many characters ( Compare from front to back )
Comparison method :
1. When str1 < str2 Return negative
2. When str1 = str2 return 0
3. When str1 > str2 Return positive number
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "ABCD";
char str2[] = "ABCE";
int ret = strncmp(str1, str2,3);
if (ret > 0)
{
printf("ret=%d:str1>str2\n", ret);
}
else if (ret < 0)
{
printf("ret=%d:str1<str2\n", ret);
}
else
{
printf("ret=%d:str1=str2\n", ret);
}
return 0;
}
3、 ... and 、 Other string functions
1.strstr function
The function prototype :char *strstr( const char *string, const char *strCharSet );
head writing Pieces of :<string.h>
The functionality : String search : stay string Search for strCharSet Whether there is ;
Parameter interpretation :
1.string --- Empty terminated string searched ;
2.strCharSet --- Empty terminated string to search ;
matters needing attention :
1. When it's found : Return a pointer strCharSet stay string The position that first appeared in ;
2. When not found : Returns a null pointer (NULL);
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "ABCD";
char str2[] = "BC";
char str3[] = "HaHa";
if (strstr(str1, str2) != NULL)
{
printf(" eureka \n");
}
else
{
printf(" Can't find \n");
}
return 0;
}
2.strtok function
The function prototype :char *strtok( char *strToken, const char *strDelimit );
head writing Pieces of :<string.h>
The functionality : String segmentation
function :
1.sep The parameter is a string , Defines the set of characters used as separators
2. The first parameter specifies a character , It contains 0 One or more by sep A token separated by one or more separators in a string
3.strtok Function found str The next mark in , And use it \0 ending , Returns a pointer to the tag .( notes :strtok Function changes the string being manipulated , So it's using strtok The string cut by the function is usually a temporary copy and can be modified .)
4.strtok The first argument of the function is not NULL , Function will find str The first mark in ,strtok Function will hold its position in the string .
5.strtok The first argument to the function is NULL , The function will start at the same position in the string that is saved , Find next tag .
6. If there are no more tags in the string , Then return to NULL The pointer
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[] = "[email protected]";
char arr2[100] = { 0 };
char sep[] = "@.";
strcpy(arr2, arr1);
char* ret = NULL;
for (ret = strtok(arr2, sep); ret != NULL;ret=strtok(NULL,sep))
{
printf("%s\n", ret);
}
return 0;
}
Four 、 Memory manipulation function
1.memcpy function
The function prototype :void *memcpy( void *dest, const void *src, size_t count );
head writing Pieces of :<memory.h>or<string.h>
The functionality : Memory copy :( It is suitable for scenarios where memory does not overlap )
function :
1. function memcpy from src The position of begins to be copied back count Bytes of data to dest Memory location for ;
2. This function is encountering \0 It doesn't stop ;
3. If source and destination There is any overlap , The results of replication are undefined ;
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
memcpy(arr1, arr1 + 4, 16);
//arr1+2 It's pointing 5 Of , Back from this position 16 Bytes of data are stored in arr1 backward 16 Bytes
// That is the 5 6 7 8 copy to 1 2 3 4 Up
for (int i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
printf("\n");
return 0;
}
2.memmove function
The function prototype :void *memmove( void *dest, const void *src, size_t count );
head writing Pieces of :<string.h>
The functionality : Memory copy :( It is suitable for scenarios with overlapping or non overlapping memory )
matters needing attention :
1. and memcpy The difference is that memmove The source and target memory blocks processed by the function can overlap .
2. If the source space and the target space overlap , You have to use memmove Function processing
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
memmove(arr1, arr1 + 2, 16);
//arr1+2 It's pointing 3 Of , Back from this position 16 Bytes of data are stored in arr1 backward 16 Bytes
// That is the 3 4 5 6 copy to 1 2 3 4 Up ( Here is memory overlap , The overlapping position is 3 4)
for (int i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
printf("\n");
return 0;
}
3.memcmp function
The function prototype :int memcmp( const void *buf1, const void *buf2, size_t count );
head writing Pieces of :<memory.h>or<string.h>
The functionality : Memory comparison :( Compare buf1 and buf2 The pointer starts with num Bytes )
Comparison method :
1. When buf1<buf2 when return <0
2. When buf1=buf2 when return =0
3. When buf1>buf2 when return >0
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
int arr1[] = { 1,2,3,4,5 };
int arr2[] = { 1,2,3,6,6 };
int ret = memcmp(arr1, arr2, 12);
// Here is a backward comparison 12 Bytes , It's a comparison 1 2 3
if (ret > 0)
{
printf("ret=%d arr1>arr2\n", ret);
}
else if (ret < 0)
{
printf("ret=%d arr1<arr2\n", ret);
}
else
{
printf("ret=%d arr1=arr2\n", ret);
}
return 0;
}
4.memset function
The function prototype :void *memset( void *dest, int c, size_t count );
head writing Pieces of :<memory.h>or<string.h>
The functionality : Memory settings (memset Function will dest One of the first count Bytes are set to characters c)
give an example :
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "almost every programmer should know memset!";
memset(str, '-', 6);// Start from the starting position and back 6 The contents of bytes are changed to '-'
puts(str);
return 0;
}
5、 ... and 、 Simulation and implementation of library functions
1. Simulation Implementation strlen function
① Recursive implementation
#include <stdio.h>
int my_strlen(const char* pa)
{
if (*pa != '\0')
{
return 1 + my_strlen(pa + 1);//1+1+1+1+1+1+0
}
else
{
return 0;
}
}
int main()
{
char arr[] = "abcdef";
int ret = my_strlen(arr);
printf("arr The length of is :%d\n", ret);
return 0;
}
② Counter implementation
#include <stdio.h>
int my_strlen(const char* pa)
{
int count = 0;
for (int i = 0; pa[i] != '\0'; i++)
{
count++;// As long as it doesn't equal \0 Plus one
}
return count;
}
int main()
{
char arr[] = "abcdef";
int ret = my_strlen(arr);
printf("arr The length of is :%d\n", ret);
return 0;
}
③ The pointer - The pointer
#include <stdio.h>
int my_strlen(const char* pa)
{
char* pa1 = pa;// First save the address of the first element
while (*pa1)
{
pa1++;// Look for \0 The address of
}
return pa1 - pa;//pa1 yes \0 The address of ,pa Is the address of the first element ; Subtract to get the number of elements
}
int main()
{
char arr[] = "abcdef";
int ret = my_strlen(arr);
printf("arr The length of is :%d\n", ret);
return 0;
}
2. Simulation Implementation strcpy function
#include <stdio.h>
#include <assert.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);// Assertion --- Determine whether these two pointers are null
char* ret = dest;
while (*dest++ = *src++)// Direct assignment , Until I met '\0' Just stop
{
;
}
return ret;
}
int main()
{
char arr1[20] = "xxxxxx";
char arr2[] = "Hello";
printf(" Before copying :%s\n", arr1);
char* ret = my_strcpy(arr1, arr2);
printf(" After copying, it is :%s\n", ret);
return 0;
}
#include <stdio.h>
#include <assert.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);// Assertion --- Determine whether these two pointers are null
int i = 0;
for (i = 0; src[i] != '\0'; i++)
{
dest[i] = src[i];// assignment , But no '\0' End mark
}
dest[i] = '\0';// Add a... At the end '\0'
}
int main()
{
char arr1[20] = "xxxxxx";
char arr2[] = "Hello";
printf(" Before copying :%s\n", arr1);
my_strcpy(arr1, arr2);
printf(" After copying, it is :%s\n", arr1);
return 0;
}
3. Simulation Implementation strcat function
#include <stdio.h>
#include <assert.h>
char* my_strcat(char* dest, const char* src)
{
assert(dest && src);// Assertion --- Determine whether these two pointers are null
while (*dest)
{
// First find dest In the array pointed to '\0' The location of
dest++;
}
while (*src)
{
*dest++ = *src++;// Add
}
}
int main()
{
char arr1[20] = "Hello ";
char arr2[] = "World";
printf(" Before addition is :%s\n", arr1);
my_strcat(arr1, arr2);
printf(" After addition is :%s\n", arr1);
return 0;
}
4. Simulation Implementation strcmp function
#include <stdio.h>
#include <assert.h>
int my_strcmp(char* str1, const char* str2)
{
assert(str1 && str2);// Assertion --- Determine whether these two pointers are null
while (*str1==*str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
return *str1 - *str2;
}
int main()
{
char arr1[] = "ABCDEF";
char arr2[] = "ABCDE";
int ret = my_strcmp(arr1, arr2);
if (ret > 0)
{
printf("ret = %d:arr1>arr2", ret);
}
else if (ret < 0)
{
printf("ret = %d:arr1<arr2", ret);
}
else
{
printf("ret = %d:arr1=arr2", ret);
}
return 0;
}
5. Simulation Implementation strncpy function
#include <stdio.h>
#include <assert.h>
char* my_strncpy(char *dest, const char *src,size_t count)
{
assert(dest && src);
char *ret = dest;
//1. Number of copied strings
while (count && (*dest++ = *src++))
{
count--;
}
//2. Not enough \0 repair
if (count)
{
while (--count)
{
*dest++ = '\0';
}
}
return ret;
}
int main()
{
char arr1[20] = "xxxxxxxx";
char arr2[] = "Hello World";
printf(" Before copying :%s\n", arr1);
char* ret = my_strncpy(arr1, arr2, 5);
printf(" After copying, it is :%s\n", ret);
return 0;
}
6. Simulation Implementation strncat function
#include <stdio.h>
#include <assert.h>
char* my_strncat(char *dest, const char *src, int count)
{
assert(dest && src);
char *ret = dest;
//1. First find \0 The location of
while (*dest++)
{
;
}
dest--;
//2. Append the source string ( According to the specified number )
while (count--)
{
//3. As long as it's not \0 Just keep adding , Append to \0 until
if (!(*dest++ = *src++))
{
return ret;
}
}
*dest = '\0';
return ret;
}
int main()
{
char arr1[20] = "Hello ";
char arr2[] = "World";
printf(" The string before appending is :%s\n", arr1);
char *ret = my_strncat(arr1, arr2, 8);
printf(" The appended string is :%s\n", ret);
return 0;
}
7. Simulation Implementation strncmp function
#include <stdio.h>
#include <assert.h>
int my_strncmp(char *str1, const char *str2, int count)
{
assert(str1 && str2);
while(count&&(*str1 == *str2))
{
if (*str1 == '\0')
return 0;
str1++;
str2++;
count--;
}
return *str1 - *str2;
}
int main()
{
char arr1[] = "Hello";
char arr2[] = "Helld";
int ret = my_strncmp(arr1, arr2, 5);
if (ret > 0)
{
printf("ret = %d:arr1>arr2", ret);
}
else if (ret < 0)
{
printf("ret = %d:arr1<arr2", ret);
}
else
{
printf("ret = %d:arr1=arr2", ret);
}
return 0;
}
8. Simulation Implementation strstr function
#include <stdio.h>
#include <assert.h>
char* my_strstr(char* str1, const char* str2)
{
assert(str1 && str2);
char* s1;
char* s2;
char* cp = str1;
// If the message is \0
if (*str2 == '\0')
{
return str1;
}
// Two cases :
// arr1-- abcdef arr1-- abbbcdef
// lookup arr2-- bcd arr2-- bbc
while (*cp)
{
s1 = cp;
s2 = str2;
while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return cp;
}
cp++;
}
return NULL;// There's no case
}
int main()
{
char arr1[] = "abbbcdef";
char arr2[] = "bcd";
char* ret = my_strstr(arr1, arr2);
if (ret == NULL)
{
printf(" Can't find \n");
}
else
{
printf(" eureka , yes :%s\n", ret);
}
return 0;
}
9. Simulation Implementation memcpy function
#include <stdio.h>
#include <assert.h>
void* my_memcpy(void* dest, const void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)src;// Cast to char*, Is to let it access the contents of one byte at a time
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
my_memcpy(arr, arr + 4, 4 * sizeof(int));
for (int i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
10. Simulation Implementation memmove function
#include <stdio.h>
#include <assert.h>
void* my_memmove(void* dest, const void* src, size_t count)
{
assert(dest && src);
void* ret = dest;
if (dest < src)
{
// Copy from front to back
while (count--)
{
// Cast to char*, Is to let it access the contents of one byte at a time
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
// Copy from back to front
while (count--)
{
*((char*)dest + count) = *((char*)src + count);
}
}
return ret;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr, arr + 2, 4 * sizeof(int));
for (int i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
11. Simulation Implementation memcmp function
#include <stdio.h>
#include <assert.h>
int my_memcmp(const void* ptr1, const void* ptr2, size_t num)
{
assert(ptr1 && ptr2);
//void* --- No concrete type pointer
//1. Can accept any type of pointer
//2. But you can't calculate
// Here, you can perform the forced conversion
while (num&&(*(char*)ptr1== *(char*)ptr2))
{
if (*(char*)ptr1 == '\0')
{
return 0;
}
(char*)ptr1+1;
(char*)ptr2+1;
num--;
}
return *(char*)ptr1 - *(char*)ptr2;
}
int main()
{
char buf1[] = "ABCDEF";
char buf2[] = "ABCDGS";
int ret = my_memcmp(buf1, buf2, 4 * sizeof(char));
if (ret > 0)
{
printf("buf1>buf2\n");
}
else if (ret < 0)
{
printf("buf1\<buf2\n");
}
else
{
printf("buf1=buf2\n");
}
return 0;
}
12. Simulation Implementation memset function
#include <stdio.h>
#include <assert.h>
void* my_memset(void* ptr, int val, size_t num)
{
assert(ptr);
for (int i = 0; i < num; i++)
{
*((char*)ptr + i) = val;
}
}
int main()
{
char str[] = "almost every programmer should know memset!";
char ch = '-';
my_memset(str, ch, 6);
puts(str);
return 0;
}
6、 ... and 、 summary
Most of the above library functions are used more , Deeply understand and firmly grasp its functions , For this problem solving will be handy , The author may not be the optimal solution in the simulation implementation , But it can help you understand and master .
边栏推荐
- Logical operator, displacement operator
- ThinkPHP uses redis to update database tables
- Development of user-defined navigation bar in uniapp
- Solution to the problem that jsp language cannot be recognized in idea
- How programmers find girlfriends through blind dates
- Difference between value and placeholder
- CLP information - how does the digital transformation of credit business change from star to finger?
- Should enterprises start building progressive web applications?
- Jerry's watch information type table [chapter]
- Rearrangement of tag number of cadence OrCAD components and sequence number of schematic page
猜你喜欢
Force buckle day32
Make drop-down menu
SQL statement
Ka! Why does the seat belt suddenly fail to pull? After reading these pictures, I can't stop wearing them
Long article review: entropy, free energy, symmetry and dynamics in the brain
Small program graduation project based on wechat reservation small program graduation project opening report reference
MySQL deadly serial question 2 -- are you familiar with MySQL index?
Huawei cloud micro certification Huawei cloud computing service practice has been stable
Setting function of Jerry's watch management device [chapter]
Small program graduation project based on wechat video broadcast small program graduation project opening report function reference
随机推荐
Difference between value and placeholder
Douban scoring applet Part-3
I don't care about you. OKR or KPI, PPT is easy for you
Why can't it run (unresolved)
Idsia & supsi & usi | continuous control behavior learning and adaptive robot operation based on Reinforcement Learning
Setting function of Jerry's watch management device [chapter]
Day05 branch and loop (II)
All in one 1412: binary classification
Logical operator, displacement operator
Notice on Soliciting Opinions on the draft of information security technology mobile Internet application (APP) life cycle security management guide
7.1 learning content
When tidb meets Flink: tidb efficiently enters the lake "new play" | tilaker team interview
be based on. NETCORE development blog project starblog - (14) realize theme switching function
The contact data on Jerry's management device supports reading and updating operations [articles]
Force buckle day32
When the watch system of Jerry's is abnormal, it is used to restore the system [chapter]
MySQL deadly serial question 2 -- are you familiar with MySQL index?
Small program graduation project based on wechat examination small program graduation project opening report function reference
Long article review: entropy, free energy, symmetry and dynamics in the brain
C import Xls data method summary III (processing data in datatable)