当前位置:网站首页>[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
边栏推荐
- Sentinel service fusing practice (sentinel integration ribbon + openfeign + fallback)
- MySQL Téléchargement et installation de la version Linux
- Nacos作为服务注册中心
- Tangle
- 程序员如何快速开发高质量的代码?
- Treatment of incomplete display of listview height
- Summary of actual business optimization scheme - main directory - continuous update
- MySQL statement
- Usage of functions decode() and replace() in SQL
- Excel intercept text
猜你喜欢
Esp32 (UART 485 communication) - 485 communication of serial port (3)
Simple use of navigation in jetpack
Résolution: cnpm: impossible de charger le fichier... Cnpm. PS1 parce que l'exécution de scripts est désactivée sur ce système
Excel intercept text
iptables初探
On iptables
根据快递单号查询物流查询更新量
The first leg of the national tour of shengteng AI developer creation and enjoyment day was successfully held in Xi'an
从技术体系到商业洞察,中小研发团队架构实践之收尾篇
Summary of actual business optimization scheme - main directory - continuous update
随机推荐
回路-通路
ctfshow-web361(SSTI)
ctfshow-web362(SSTI)
Nacos作为服务配置中心实战
Click the input box to pop up the keyboard layout and move up
在渤海期货办理开户安全吗。
Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha
Machine learning practice - naive Bayes
MySQL Téléchargement et installation de la version Linux
mysql_linux版本的下载及安装详解
C language simulates entering and leaving the stack, first in first out, first in first out, shared memory
Minesweeping II of souI instance
解决:cnpm : 無法加載文件 ...\cnpm.ps1,因為在此系統上禁止運行脚本
Teach you to quickly rename folder names in a few simple steps
From technical system to business insight, the closing chapter of the practice of small and medium-sized R & D team structure
Sentinel service fusing practice (sentinel integration ribbon + openfeign + fallback)
纠结
Nacos cluster construction and MySQL persistence configuration
【历史上的今天】4 月 23 日:YouTube 上传第一个视频;网易云音乐正式上线;数字音频播放器的发明者出生
Use of kotlin collaboration in the project