当前位置:网站首页>[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
边栏推荐
猜你喜欢

12个例子夯实promise基础

7、 DOM (Part 2) - chapter after class exercises and answers

On iptables

STM32: LCD显示

Ctfshow - web362 (ssti)

listener. log

Solutions such as unknown or garbled code or certificate problem prompt in Charles's mobile phone packet capture, actual measurement.

ctfshow-web362(SSTI)

iptables初探

视频边框背景如何虚化,简单操作几步实现
随机推荐
Nacos cluster construction and MySQL persistence configuration
RPM package management
Seata handles distributed transactions
C language simulates entering and leaving the stack, first in first out, first in first out, shared memory
特征选择feature_selection--SelectKBest
Esp32 (UART 485 communication) - 485 communication of serial port (3)
Deeply understand what new and make in golang are and what are the differences?
ctfshow-web362(SSTI)
Dynamically add and delete layouts
The first leg of the national tour of shengteng AI developer creation and enjoyment day was successfully held in Xi'an
Click the input box to pop up the keyboard layout and move up
解决:cnpm : 無法加載文件 ...\cnpm.ps1,因為在此系統上禁止運行脚本
Download xshell 6 and xftp6 official websites
2022.04.23(LC_714_买卖股票的最佳时机含手续费)
Use of kotlin collaboration in the project
WebView opens H5 video and displays gray background or black triangle button. Problem solved
K210 serial communication
Resolution: cnpm: unable to load file \cnpm. PS1, because running scripts is prohibited on this system
ctfshow-web361(SSTI)
Implementation of TCP UDP communication with golang language