当前位置:网站首页>[advanced level 11 of C language -- character and string functions and their simulation implementation (2)]
[advanced level 11 of C language -- character and string functions and their simulation implementation (2)]
2022-04-23 18:53:00 【Beginners of C language】
Character and string functions and their simulation implementation (2)
Preface
This article goes on to learn about character and string functions , And simulated with code . The main learning contents include :
4、 String search
- strstr
- strtok
5、 Error message report
- strerror
6、 Character manipulation functions
7、 Memory manipulation function
- memcpy
- memmove
- memset
- memcmp
4、 String search
4.1 Library function strstr
char * strstr ( const char *str1, const char * str2);
- Return to point str1 The first one to appear str2 The pointer to , If str2 No str1 Part of , Return null pointer
int main()
{
char a1[] = "abbbcdef";
char a2[] = "bbc";
char* ret = strstr(a1, a2);
if (NULL==ret)
{
printf(" Could not find substring \n");
}
else
{
printf("%s\n", ret);
}
}
4.2 Simulate the implementation of library functions strstr
char* my_strstr(const char* p1, const char* p2)
{
assert(p1&&p2);
const char* s1 = p1;// Give the pointer the initial position
const char* s2 = p2;// Give the pointer the initial position
const char* cur = p1;// Record the current pointer position of the string
while (*cur)
{
s1 = cur;
s2 = p2;// Move to the initial position
while (*s1 && *s2 && (*s1==*s2))
{
s1++;// When equal , Pointer backward , Until two are not equal or one is 0
s2++;
}
if (*s2=='\0')
{
return (char*)cur;
}
cur++;// It's not equal , Current pointer plus 1
}
// Jump out of , It's just a string 1 Move to the end
return NULL;
}
int main()
{
char a1[] = "abbbcdef";
char a2[] = "bbc";
char* ret = my_strstr(a1, a2);
if (NULL==ret)
{
printf(" Could not find substring \n");
}
else
{
printf("%s\n", ret);
}
}
The results are as follows :

4.3 Library function strtok
char * strtok ( char * str, const char * sep );
- sep The parameter is a string , Defines the set of characters used as delimiters. 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
- strtok Function found str The next mark in , And use it \0 ending , Returns a pointer to the tag
- 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
- 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
- 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
- If there are no more tags in the string , Then return to NULL The pointer
int main()
{
char a[] = "[email protected]@hello world";
char a2[50] = {
0 };
strcpy(a2, a);
printf("%s\n", a2);
const char* sep = "@. ";// Three separators
printf("%s\n", strtok(a2, sep));//learnC
printf("%s\n", strtok(NULL, sep));//day
printf("%s\n", strtok(NULL, sep));//day
return 0;
}
The results are as follows :


int main()
{
char a[] = "[email protected]@hello world";
char a2[50] = {
0 };
strcpy(a2, a);
printf("%s\n", a2);
const char* sep = "@. ";// Three separators
char* str = NULL;
// Find multiple strings separated by circular separators , Not empty , Just find the next one , Until the end
for (str =strtok(a2,sep); str != NULL; str=strtok(NULL,sep))
{
printf("%s\n", str);
}
return 0;
}
The results are as follows :

5、 Error message report
5.1 Library function strerror
char * strerror ( int errnum );
- Return error code , The corresponding error message
int main()
{
int* p = (int*)malloc(INT_MAX);// Apply for memory in heap
if (p==NULL)
{
printf("%s\n", strerror(errno));// Print error message
return 1;
}
return 0;
}
The results are as follows :

6、 Character manipulation functions
| function | If his parameters meet the following conditions, it returns true |
|---|---|
| iscntrl | Any control character |
| isspace | Blank character : Space ‘ ’, Change the page ‘\f’, Line break ’\n’, enter ‘\r’, tabs ’\t’ Or vertical tabs ’\v’ |
| isdigit | Decimal number 0~9 |
| isxdigit | Hexadecimal number , Include all decimal digits , Lowercase letters a-f, Capital A~ F |
| islower | Lowercase letters a~z |
| isupper | Capital A~Z |
| isalpha | Letter a-z or A~Z |
| isalnum | Letters or numbers ,a-z, A-Z, 0~9 |
| ispunct | Punctuation , Any graphic character that is not a number or letter ( Printable ) |
| isgraph | Any graphic character |
| isprint | Any printable character , Including graphic characters and white space characters |
7、 Memory manipulation function
7.1 Library function memcpy
void * memcpy ( void * destination, const void * source, size_t num );
- function memcpy from source The position of begins to be copied back num Bytes of data to destination Memory location for
- This function is encountering ‘\0’ It doesn't stop
- If source and destination There is any overlap , The results of replication are undefined
int main()
{
int a1[10] = {
1,2,3,4,5,6,7,8,9,10 };
int a2[5] = {
0 };
memcpy(a2, a1, 20);
int sz = sizeof(a1) / sizeof(a1[0]);
for (int i = 0; i < sz; i++)
{
printf("%d\n", a2[i]);
}
return 0;
}
7.2 Simulate the implementation of library functions memcpy
// Simulation Implementation
void* my_memcpy(void* dest, const void* src, size_t cnt)
{
assert(dest&&src);
void* ret = dest;// Receive any type of data
while (cnt--)
{
*(char*)dest = *(char*)src;// Swap in byte order
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int a1[10] = {
1,2,3,4,5,6,7,8,9,10 };
int a2[5] = {
0 };
my_memcpy(a2, a1, 20);
int sz = sizeof(a1) / sizeof(a1[0]);
for (int i = 0; i < sz; i++)
{
printf("%d\n", a2[i]);
}
return 0;
}
The results are as follows :


7.3 Library function memmove
void * memmove ( void * destination, const void * source, size_t num );
- and memcpy The difference is that memmove The source and target memory blocks processed by the function can overlap
- If the source space and the target space overlap , You have to use memmove Function processing
int main()
{
int a1[10] = {
1,2,3,4,5,6,7,8,9,10 };
memmove(a1+2, a1, 20);
int sz = sizeof(a1) / sizeof(a1[0]);
for (int i = 0; i < sz; i++)
{
printf("%d\n", a1[i]);
}
return 0;
}
7.4 Simulate the implementation of library functions memmove
// Simulation Implementation
void* my_memmove(void* dest, const void* src, size_t cnt)
{
assert(dest&&src);
void* ret = dest;
if (dest<src)
{
// Copy from left to right
while (cnt--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
// From right to left
while (cnt--)
{
*((char*)dest + cnt) = *((char*)src + cnt);
}
}
return ret;
}
int main()
{
int a1[10] = {
1,2,3,4,5,6,7,8,9,10 };
my_memmove(a1+2, a1, 20);
int sz = sizeof(a1) / sizeof(a1[0]);
for (int i = 0; i < sz; i++)
{
printf("%d\n", a1[i]);
}
return 0;
}
The results are as follows :

7.5 Library function memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
- Compare from ptr1 and ptr2 The pointer starts with num Bytes
- Return value less than 0, The data of the preceding byte is smaller than the data of the following corresponding byte
- The return value is equal to 0, The data of the preceding byte is equal to the data of the following corresponding byte
- Return value greater than 0, The data of the preceding byte is larger than the data of the following corresponding byte
int main()
{
int a1[] = {
1,2,3,4,5 };
int a2[] = {
1,2,3,4,0x11223305 };
int ret = memcmp(a1, a2, 18);
printf("%d\n", ret);
return 0;
}
The results are as follows :

7.6 Library function memset
void *memset( void *dest, int c, size_t count );
- memset Function will Target space dest Of in total count The contents of bytes are set to characters c.
int main()
{
int a[] = {
0x11111111,0x22222222,3,4,5 };
memset(a, 6, 20);
return 0;
}
The results are as follows :

summary
The learning of string library function is basically over . It's a little confusing after learning , This content can be used as a dictionary , Check again when necessary .
It feels a little boring to learn string library functions alone , You can understand and master the usage of these functions only after you brush the questions later .
Library functions to achieve learning dazzling , There's one more thing I haven't written completely , Add content later .
The next article updates the content related to structure .
版权声明
本文为[Beginners of C language]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231851188685.html
边栏推荐
- ESP32 LVGL8. 1 - label (style 14)
- SQL中函数 decode()与 replace()的用法
- MVVM model
- Deeply understand what new and make in golang are and what are the differences?
- Practice of Druid SQL and security in meituan review
- Treatment of incomplete display of listview height
- 机器学习理论基础篇--关于机器学习的一些术语
- Sogou cell thesaurus analysis (only extract words and word frequency)
- Tencent map and high logo removal method
- ESP32 LVGL8. 1 - roller rolling (roller 24)
猜你喜欢

Query the logistics update quantity according to the express order number

Setting up keil environment of GD single chip microcomputer

The first leg of the national tour of shengteng AI developer creation and enjoyment day was successfully held in Xi'an

MySQL Téléchargement et installation de la version Linux

ESP32 LVGL8. 1 - img picture (IMG 20)

使用 bitnami/postgresql-repmgr 镜像快速设置 PostgreSQL HA

Esp32 (UART 485 communication) - 485 communication of serial port (3)

教你用简单几个步骤快速重命名文件夹名

After opening the original normal project, the dependency package displays red and does not exist.

Summary of actual business optimization scheme - main directory - continuous update
随机推荐
The type initializer for ‘Gdip‘ threw an exception
Machine learning theory (8): model integration ensemble learning
Configure iptables
12个例子夯实promise基础
Esp32 drive encoder -- siq-02fvs3 (vscade + IDF)
Simplified path (force buckle 71)
Sentinel服务熔断实战(sentinel整合ribbon+openFeign+fallback)
Nacos cluster construction and MySQL persistence configuration
[mathematical modeling] - analytic hierarchy process (AHP)
Introduction to ROS learning notes (II)
Sogou cell thesaurus analysis (only extract words and word frequency)
MVVM model
K210串口通信
Actual combat of Nacos as service configuration center
One of the reasons why the WebView web page cannot be opened (and some WebView problem records encountered by myself)
关于unity文件读取的操作(一)
解决:cnpm : 無法加載文件 ...\cnpm.ps1,因為在此系統上禁止運行脚本
【科普】CRC校验(一)什么是CRC校验?
iptables初探
Machine learning theory (7): kernel function kernels -- a way to help SVM realize nonlinear decision boundary