当前位置:网站首页>String and memory functions
String and memory functions
2022-07-26 06:47:00 【Xiao Liu L】
Catalog
Character classification function
Two Simulation and implementation of library functions
2.1 Simulation Implementation strlen
2.2 Simulation Implementation strcpy
2.3 Simulation Implementation strcat
2.4 Simulation Implementation strstr
2.5 Simulation Implementation strcmp
2.6 Simulation Implementation memcpy
2.7 Simulation Implementation memmove
Inspirational link
Luminescence is not the patent of the sun , Everyone can .
Key points of this chapter
This paper focuses on the use and precautions of library functions dealing with characters and strings
Find the string length strlen
Unlimited length string function strcpy strcat strcmp
Introduction to string functions with limited length strncpy strncat strncmp
String search strstr strtok
Error message report strerror
Character manipulation
Memory manipulation function memcpy memmove memset memcmp
C The processing of characters and strings in languages is very frequent , however C The language itself has no string type , Strings are usually placed in
Constant string Medium or A character array in .
String constant For string functions that do not modify it .
One Function introduction
1.1 strlen
In the previous article , Three methods are introduced to realize strlen:(1) The method of counting (2) Recursive method (3) The pointer - Pointer method .
size_t strlen ( const char * str );
sizeof Is an operator , The result returned is size_t (size_t Specially for sizeof The return value of is designed )
size_t amount to unsigned int
Library function strlen Return value yes size_t, therefore strlen Cannot be used to add or subtract :strlen("abc") - strlen("abcdefg") The result will be a size_t Number of types , Will not be -4 ( terms of settlement , Can force conversion )
String to '\0' As an end sign ,strlen Function returns in a string '\0' The number of characters that appear before ( It doesn't contain '\0' )
The string that the argument points to must be in '\0' end .
Note that the return value of the function is size_t, It's unsigned ( Fallible )
Learn to strlen Simulation Implementation of function
1.2 strcpy
char* strcpy(char * destination, const char * source );
The source string must be in '\0' end .
In the source string '\0' Copy to target space .
The target space has to be large enough , To ensure that the source string can be stored .(strlen No matter the target space can be put in , But we should ensure that the target space is large enough , So that it can be put in )
The target space has to be variable .
Learn to simulate
1.3 strcat
Append a string
char * strcat ( char * destination, const char * source );
The source string must be in '\0' end . No, \0 Words , You cannot add , Can't print out .
The target space must be large enough , It can hold the contents of the source string .
The target space must be modifiable .
The string appends itself , how ?
Code display :
#include <stdio.h>
int main()
{
char arr1[30] = "hello";
char arr2[] = "world";
strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
1.4 strcmp
int strcmp ( const char * str1, const char * str2 );
The first string is larger than the second string , Return greater than 0 The number of
The first string is equal to the second string , Then return to 0
The first string is less than the second string , Then return less than 0 The number ofstrcmp(s1, s2), Compare string sizes , The two strings are compared character by character from left to right ( Press ASCII Compared with the value of ), The comparison is not stopped until a certain character is not equal or one of the strings is compared , The comparison of characters is ASCII Code comparison ( If the string 1 Greater than string 2, The return result is greater than 0, If the string 1 Less than string 2, The return result is less than 0, If the string 1 Equal to string 2, The return result is equal to 0.)
strcmp The header file for is <string.h>
1.5 strncpy
char * strncpy ( char * destination, const char * source, size_t num );
Copy num Characters from the source string to the target space .
If the length of the source string is less than num, After copying the source string , Add... After the target '\0', until num individual .
1.6 strncat
char * strncat ( char * destination, const char * source, size_t num )
Append character , Additional num Characters from the source string to the target space .
If the length of the source string is greater than num, Then add num Source string after , Add another one at the back '\0'.If the length of the source string is less than num, Then append it The source string after , Add another one behind '\0', Nothing else .
1.7 strncmp
int strncmp ( const char * str1, const char * str2, size_t num );
Compare num Characters
1.8 strstr
char * strstr ( const char *str1, const char * str2);
String lookup function , stay str1 In looking for str2, Back in the str1 For the first time str2 The address of . Return null pointer not found .
Code display :
#include <stdio.h>
int main()
{
char arr1[] = "abcdabcd";
char arr2[] = "cd";
char* ret = strstr(arr1, arr2);
if (ret == NULL)
printf(" Can't find ");
else
printf("%s\n", ret);
return 0;
}
1.9 strtok
char * strtok ( char * str, const char * sep );
(1)sep The parameter is a string , Defines the set of characters used as separators
(2) The first parameter specifies a string , It contains 0 One or more by sep A mark separated by one or more separators in a string .
(3)strtok Function found str The next mark in , And use it \0 ending , Return a point The pointer to this marker ( notes : strtok Function changes the string being manipulated , So it's using strtok The string segmented by function is usually the content of temporary copy And it can be modified .)
Change the content of the tag to \0, Will change the content of the string , So copy the string temporarily .
(4)strtok The first argument of the function is not NULL , Function will find str The first mark in ,strtok The function will save it in the string Position in .
(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 the next target remember .
(6) If there are no more tags in the string , Then return to NULL The pointer .
1 strtok When the function finds the first tag , The first argument to the function is not NULL
2 strtok When the function finds a non first tag , The first argument to the function is NULL
Code display :
#include <stdio.h>
int main()
{
const char* p = "@.";
char arr[] = "[email protected]";
char buf[50] = { 0 };// Because the string will be modified , So go ahead arr Temporarily copy to buf in
// Make sure that arr Not modified
strcpy(buf, arr);// Temporary copy
char* str = strtok(buf, p);
printf("%s\n", str);
str = strtok(NULL, p);
printf("%s\n", str);
str = strtok(NULL, p);
printf("%s\n", str);
return 0;
}
Code display :( This code is more convenient )
#include <stdio.h>
int main()
{
const char* p = "@.";
char arr[] = "[email protected]";
char buf[50] = { 0 };// Because the string will be modified , So go ahead arr Temporarily copy to buf in
// Make sure that arr Not modified
strcpy(buf, arr);// Temporary copy
char* str = NULL;
for (str = strtok(buf, p); str != NULL; str = strtok(NULL, p))
{
printf("%s\n", str);
}
return 0;
}1.10 strerror
char * strerror ( int errnum );
Return error code , The corresponding error message ( Translate the error code into error message )
C The language specifies some information
Error code — error message
0—No Error
1— …
2—…
When library functions are used , When something goes wrong, it will errno This global error variable is set to the error code generated by this execution of the library function .
errno yes C Global variables provided by language , You can use it directly , Put it in errno.h This file , So you have to quote
#include <errno.h> strerror(errno); Will show the error
Code display :
#include <stdio.h>
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%s\n", strerror(i));
}
return 0;
}
Character classification function
The above figure shows the character classification function , for example :isspace, If it's white space , Return to non 0. Return if it is not a blank character 0.
Other uses are similar to this .
Code display :
#include <stdio.h>
#include <ctype.h>
int main()
{
printf("%d\n", isspace(' '));
return 0;
}
Character conversion function
int tolower(int c);
int toupper(int c);
#include <stdio.h>
int main()
{
char ch = 0;
ch = getchar();
if (islower(ch))
{
ch = toupper(ch);
}
else
{
ch = tolower(ch);
}
printf("%c\n", ch);
return 0;
}toggle case

1.11 memcpy
void * memcpy ( void * destination, const void * source, size_t num );
(1) function memcpy from source The position of begins to be copied back num individual byte Data to destination 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 . If destination stay source Behind , It may lead to just changed destination The content of , It's changed again. source. It will lead to repetition . In this case, it is recommended to use memmove, It won't happen .
Code display :
#include <stdio.h>
int main()
{
char arr1[] = "sjhjcd";
char arr2[50] = { 0 };
strcpy(arr2, arr1);// Copy string
int arr3[] = { 1, 2,3,4,5,6,7 };
int arr4[5] = { 0 };
memcpy(arr4, arr3, 20);// Everything can be copied , Not sure what to copy
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", arr4[i]);
}
return 0;
}
C Language only requires memcpy It is enough to copy non overlapping memory space ,memmove To deal with those overlapping memory space . however VS Of memcpy Can handle overlapping memory copies , You can also handle non overlapping memory copies .
1.12 memmove
void * memmove ( void * destination, const void * source, size_t num );
(1) and memcpy The difference is that memmove The source memory block and target memory block processed by the function can be Overlapping .
(2) If the source space and the target space overlap , You have to use memmove Function processing .
memmove You can also handle non overlapping .
1.13 memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
(1) Compare from ptr1 and ptr2 The pointer starts with num Bytes
(2) The return value is as follows :

Compare bytes , Equal words , return 0. The comparison is ASCII value .
1.14 memset
Code display :
#include <stdio.h>
int main()
{
char arr[20] = { 0 };
memset(arr, 'x', 10);
return 0;
}Change in bytes .
Two Simulation and implementation of library functions
2.1 Simulation Implementation strlen
1 The method of counting
#include <stdio.h>
#include <assert.h>
int my_strlen(const char* str)
{
assert(str);
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
int len = 0;
len = my_strlen("abcdefg");// Pass to my _strlen It's the character 'a' The address of
printf("%d", len);
return 0;
}\0 Of ASCII The code value is 0 , A flag indicating the end of the string , This is an escape character , The whole is regarded as one character , Stored in memory as 0000 0000
Characters are in memory with ASCII The binary complement corresponding to the code value exists (8 position )
2.2 Simulation Implementation strcpy
Code display :
#include <stdio.h>
#include <assert.h>
char* my_strcpy(char* a, const char* b)
{
assert(a && b);
char* ret = a;
while (*a++ = *b++)//++ Is greater than * The priority of the
{
;
}
return ret;
}
int main()
{
char arr1[20] = { 0 };
char arr2[] = "hello";
printf("%s\n", my_strcpy(arr1, arr2));// Chained access to functions
return 0;
}Try not to return the address of a local variable ( The function called , Local variables inside , It may be destroyed after use , The value of the local variable pointed to by the address , It may change ), Not local variables .
2.3 Simulation Implementation strcat
Code display :
#include <stdio.h>
#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[30] = "hello";
char arr2[] = "world";
my_strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}Ideas :(1) Find... In the target space \0 (2) Append character
everyting—— Search for strcat—— Right click Open the path
2.4 Simulation Implementation strstr
Code display :
#include <stdio.h>
#include <assert.h>
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
if (*str2 == '\0')
{
return (char*)str1;//(const char* and char* It's different )
}
// When the first character matches , When there is a mismatch in the subsequent letters , The address of the string should return to the first character where the match occurs , Address of the next character of ,
// So try not to use it directly str1 and str2, But indirectly
const char* s1 = str1;
const char* s2 = str2;
const char* s3 = str1;// I've been... Until I meet the first character that matches +1
while (*s3)// In this cycle ,s3 Has been +1, Until s3 encounter \0 ,while end
{
s1 = s3;
s2 = str2;
while (*s1 != '\0' && *s2 != '\0' && * s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
return (char*)s3;
s3++;
}
return NULL;
}
int main()
{
char arr1[] = "abcdabcd";
char arr2[] = "A";
char* ret = my_strstr(arr1, arr2);
if (ret == NULL)
printf(" Can't find ");
else
printf("%s\n", ret);
return 0;
}2.5 Simulation Implementation strcmp
Code display :
#include <stdio.h>
#include <assert.h>
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
if (*str1 > *str2)
return 1;
else
return -1;
}
int main()
{
char arr1[] = "abc";
char arr2[] = "abcd";
int ret = my_strcmp(arr1, arr2);
printf("%d", ret);
return 0;
}"abcd" and "abc" Compare , yes 1 because , The first string is d Of ASCII, The last string is '\0' Of ascii, So it is 1.
2.6 Simulation Implementation memcpy
Code display :
#include <stdio.h>
#include <assert.h>
void* my_memcpy(void* dest, const void* src, size_t num)
{
void* ret = dest;
assert(dest && src);
while (num--)// After --, Try it first , after --;
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr3[] = { 1, 2,3,4,5,6,7, 8, 9, 10 };
int arr4[5] = { 0 };
my_memcpy(arr4, arr3, 20);
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", arr4[i]);
}
return 0;
}Knowledge point :
(1)void* You can't add or subtract , So convert to char * Add and subtract .
2.7 Simulation Implementation memmove
Code display :
#include <stdio.h>
#include <assert.h>
void* my_memmove(void* dest, const void* src, size_t num)// You can't create a space without creating a space
{
void* ret = dest;
assert(dest && src);
if (dest < src)
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
while (num--)
{
*((char*)dest + num) = *((char*)src+num);
}
}
return ret;
}
#include <stdio.h>
int main()
{
int arr3[] = { 1, 2,3,4,5,6,7, 8, 9, 10 };
my_memmove(arr3+1, arr3, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr3[i]);
}
return 0;
}边栏推荐
- Torth file read vulnerability (cnvd-2020-27769)
- 『HarmonyOS』DevEco的下载安装与开发环境搭建
- 从Architecture带你认识JVM
- 源代码加密技术发展阶段
- Click "Niuke | daily question" to eliminate it
- Is there any online account opening process of Huatai Securities? Is online account opening safe
- 原生高性能抓包工具Proxyman,送给爱学习的你
- 归并排序(merge_sort)
- Go的map字典及约束
- XSS-labs(1-10)闯关详解
猜你喜欢

Force buckle - 3. Longest substring without repeated characters

7. Reverse Integer整数反转

『HarmonyOS』工程的创建与虚拟机的使用
![Esxi 7.0 installation supports mellanox technologies mt26448 [connectx en 10gige, PCIe 2.0 5gt/s] driver, and supports the cheapest 10GB dual fiber network card](/img/51/a5282b657b1dfed2dac476c1efee2d.png)
Esxi 7.0 installation supports mellanox technologies mt26448 [connectx en 10gige, PCIe 2.0 5gt/s] driver, and supports the cheapest 10GB dual fiber network card

UIToolkit工具模板工程

UIToolkit中显示汉字

Delete ^m from VIM

"Harmonyos" explore harmonyos applications
![[graduation season _ advanced technology Er] farewell to yourself who has been confused for the past two years. Regroup, junior I'm coming](/img/04/3121514fcd8fcf1c939cbca7f4c67a.jpg)
[graduation season _ advanced technology Er] farewell to yourself who has been confused for the past two years. Regroup, junior I'm coming

The "darkest hour" has not come yet. Cherish every bullet 2020-03-22
随机推荐
UIToolkit中显示汉字
Click "Niuke | daily question" to eliminate it
抖音web端 s_v_web_id 参数生成分析与实现
Esxi 7.0 installation supports mellanox technologies mt26448 [connectx en 10gige, PCIe 2.0 5gt/s] driver, and supports the cheapest 10GB dual fiber network card
Summarize and learn STM32 to create project template
『期末复习』16/32位微处理器(8086)基本寄存器
深度学习——CV、CNN、RNN
Overview of image classification of vision transformer must read series
Heap sort
Ruby on rails Code Execution Vulnerability (cve-2020-8163) technical analysis, research, judgment and protection
MySQL基础篇(二)-- MySQL 基础
【图像去噪】基于双立方插值和稀疏表示实现图像去噪matlab源码
Use and analysis of show profile optimized by MySQL
How does the seckill system ensure that the database does not crash and prevent oversold goods
PMP customs formula, don't hurry to recite it
[nanny level] package volume optimization tutorial
What are the main reasons for server crash
@Constructorproperties annotation understanding and its corresponding usage
Fastdfs supports dual IP and IPv6
C#使用log4net插件,输出日志到文件