当前位置:网站首页>String functions that you need to know
String functions that you need to know
2022-07-03 15:23:00 【Little snail rushes towards】
Preface
do person : Little snail rushes forward
quotes : I can accept failure , But I can't accept giving up
If you think the blogger's article is good , Please
give the thumbs-up , Collection , Follow and support bloggers . If you find any problems, you are welcome * Please make corrections in the comments section .
This blogger will continue to supplement the string function in the previous blog .
Catalog
Introduction to string functions with limited length
Character classification function
Introduction to string functions with limited length
What string function with limited length ? It is a string function with unlimited length (strcmp,strcpy,strcat) These functions they all encounter '\0' Will stop the function , But there will be some unsafe situations , With strcpy Example of string copy function , When the storage space of the target string is smaller than that of the source string , The copy will still proceed , This causes the program to crash .
therefore , In order to use the corresponding functions more safely , Strings with limited length are naturally (strncmp,strncpy,strncant). Next, I will analyze for you one by one .
strncpy function
Definition
Parameters
strncpy(strDest,strSource,count);
Among them strDest finger Target string .
strSource finger The source string .
count Refers to the... To be copied from the source string to the target string The number of characters .
Example implementation
int main()
{
char arr1[5] = "he";
char arr2[10] = "hehewang";
strncpy(arr1, arr2, 4);// Restricted copy of string
printf("%s\n", arr1);
return 0;
}
Let's go on Simulation Implementation strncpy function
char* my_strncpy(char* dest, char* source, size_t count)
{
assert(dest && source);// Assertion
char* start = dest;// Save the address of the target string
while (count && (*dest++ = *source++) != '\0')
{
count--;// Each copy of a character to be copied is one less
}
if (count)// if conut The number of characters is greater than the number of copies
while (--count)
*dest++ = '\0';// The excess part is set 0
return (start);
}
about strncpy Is a function that appears for safer use of string copying .
function :
How many characters can be copied according to your needs .
The header file :
<string.h>.
Return value :
The first address of the target string is returned .
strncmp function
Definition
Parameters
strncmp(str1,str2,count);
Return value
We know strncmp and strcmp The function of is extremely similar , but strncmp What is more brilliant is that we can compare the characters we want .
Illustrate with examples
int main()
{
char* p1 = "abcdfeg";
char* p2 = "abed";
int ret = strncmp(p1, p2, 3);
if (ret > 0)
{
printf("p1>p2\n");
}
else if (ret < 0)
{
printf("p1<p2\n");
}
else
{
printf("p1=p2");
}
return 0;
}
simulation strncpy
int my_strncmp(const char* p1, const char* p2, size_t count)
{
assert(p1 && p2);// Assertion
// First, judge whether they are equal
while ((*p1 == *p2)&&count)
{
count--;// Every character is judged --
if (count==0)
{
return 0;//p1==p2
}
p1++;
p2++;
}
return (*(unsigned char*)p1 - *(unsigned char*)p2);// return
}
function
Limited comparison of string longitude
The header file
<string.h>
strncat function
Definition
Parameters
strncat(dest,Soure,count);
strncat Is a limited append string .
The return value is the first address of the returned target string
The header file <string.h>
Illustrate with examples
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[10] = "menace";
char arr2[5] = "mehe";
strncat(arr1, arr2, 2);
printf("%s\n", arr1);
return 0;
}
Simulation Implementation
char* my_strncat(char* dest, const char* source, size_t count)
{
assert(dest && source);// Assertion
// Find the destination string '\0'
char* start = dest;
while (*dest != '\0')
{
dest++;
}
while (count && (*dest++ = *source++))// Add
{
count--;
}
*dest = '\0';// Put the end of the string at the end of the target string
return start;
}
There may be no doubt , The first address of the return target string is used above ? What I think of for the moment is that it is easy to print strings .
String lookup function
Now I will mainly introduce C Language string lookup function (strstr,strtok)
strstr function
Definition
Parameters
strstr(str1,str2);
function
strstr Function to find substring , It's a search str1 Whether there is str2 Substring of
Return value
Return to point str1 For the first time in str2 The pointer to , If the substring does not exist , Then return the null pointer .
The header file
<string.h>
Illustrate with examples
int main()
{
char* p1 = "amcdefme";
char* p2 = "def";
char* ret = strstr(p1, p2);// Store the return value of the function
if (NULL == ret)
{
printf(" Substring does not exist \n");
}
else
{
printf("%s\n", ret);// Print the substring found
}
return 0;
}
Notice if there is a string , The first address of the first occurrence of the substring returned by the function .
Simulation Implementation strstr
char* my_strstr(const char* p1, const char* p2)
{
assert(p1 && p2);// Assertion
char* s1 = NULL;
char* s2 = NULL;// Prepare two char* Null pointer of type
char* pt = (char*)p1;// Store the starting address of the found substring
// Judge p2 Null pointer or not
if (*p2 == '\0')
{
return (char*)p1;// Substring must exist
}
// Start looking for substrings
while (*pt)
{
s1 = pt;// Point to the location to find
s2 = (char*)p2;// Point to the substring you want
while (*s1 && *s2 && (*s1 == *s2))// Analyze whether the strings are equal one by one , So as to infer whether the substring exists
{
s1++;
s2++;
}
if ('\0' == *s2)// Description found substring
{
return pt;// Returns the first address of the first occurrence of a substring
}
pt++;// If you don't find it, keep looking down
}
return (char*)NULL;// Did not find
}
This simulation implementation is still classic , Interested partners can try .
strtok function
Definition
Parameters
strtok(strToken,strDelimit)
strDelimit The parameter is a string , Defines the set of characters used as separators
The first parameter specifies a string , It contains 0 One or more by strDelimi A mark separated by one or more separators in a string .
strtok function find strToken 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 segmented by function is usually the content of temporary copy And it can be modified .)
strtok Functional The first parameter is not NULL, Function will find strToken The first mark in ,strtok Function will hold its position in the string .
strtok Functional The first parameter is zero 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 .
strtok Illustrate with examples
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
char arr[] = "[email protected]*100";// character string
char p[] = "[email protected]*";// Separator
char* ret = NULL;
for (ret = strtok(arr, p);ret != NULL;ret = strtok(NULL, p))
{
printf("%s\n",ret);// Print split strings
}
return 0;
}
Report error messages
Now I will continue to share with you , Report error message function strerror function
Definition
Parameters
strerror function
Can get system error messages (strerror) Or print the error message provided by the user (_strerror).
Return value :
strerror and _strerror Returns a pointer to the error message string . Yes strerror or _strerror Subsequent calls to may overwrite the string .
The header file :
<string.h>
Illustrate with examples
char* str = strerror(errno)
//errno Is a global error code variable
// When C Language library functions in the process of execution , Something went wrong , The corresponding error code , Assign values to the errno.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
FILE* pf = fopen("test.txt", "r");// Find files
if (pf == NULL)
{
printf("%s\n", strerror(errno));
}
else
{
printf("open file success\n");
}
return 0;
}
Be careful :
We borrow it here fopen function Functions that can open files , Among them Parameters 1( Documents ), Parameters 2( It refers to the way to open the file )
FILE* It's a pointer type .
Here, when the system cannot read this file , adopt strerror(errno) We can show the error message to us .
about strerror Function summary :
strerror() The error in the process of code execution , It's reported .
strerror() The parameter is 1,2,3,4,5....... This type of error code , We can use errno Global static variables receive .
Character classification function
stay c There are many character classification functions in language , Now let's use charts to show :
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' |
sdigit | 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 |
Next, we will explain some character classification functions
islower function Determine whether the character is lowercase
Definition
Parameters
Illustrate with examples
int main()
{
char ret = 0;
scanf("%c", &ret);
if (islower(ret) != '\0')
{
printf(" Lowercase letters \n");
}
else
{
printf(" Not lowercase \n");
}
return 0;
}
Now I won't continue to introduce you , If you are interested , You can start to study .
summary
In this blog , It mainly introduces ,strncpy,strncmp,strncat These restricted string functions ; And character lookup function strstr( Find substrings ),strtok( Find a string separated by a delimiter ); And Report error message function strerror and Character classification function .
边栏推荐
- Redis主从、哨兵、集群模式介绍
- Tensorflow realizes verification code recognition (I)
- [attention mechanism] [first vit] Detr, end to end object detection with transformers the main components of the network are CNN and transformer
- socket. IO build distributed web push server
- qt使用QZxing生成二维码
- 如何使用 @NotNull等注解校验 并全局异常处理
- MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)
- Puppet automatic operation and maintenance troubleshooting cases
- Using Tengine to solve the session problem of load balancing
- Finally, someone explained the financial risk management clearly
猜你喜欢
视觉上位系统设计开发(halcon-winform)-5.相机
Redis主从、哨兵、集群模式介绍
Can‘t connect to MySQL server on ‘localhost‘
Final review points of human-computer interaction
Concurrency-01-create thread, sleep, yield, wait, join, interrupt, thread state, synchronized, park, reentrantlock
百度智能云助力石嘴山市升级“互联网+养老服务”智慧康养新模式
Characteristics of MySQL InnoDB storage engine -- Analysis of row lock
Digital image processing -- popular Canny edge detection
Influxdb2 sources add data sources
【可能是全中文网最全】pushgateway入门笔记
随机推荐
Digital image processing -- popular Canny edge detection
Leasing cases of the implementation of the new regulations on the rental of jointly owned houses in Beijing
Summary of concurrent full knowledge points
Tensorflow realizes verification code recognition (I)
驱动与应用程序通信
[attention mechanism] [first vit] Detr, end to end object detection with transformers the main components of the network are CNN and transformer
High quality workplace human beings must use software to recommend, and you certainly don't know the last one
什么是one-hot encoding?Pytorch中,将label变成one hot编码的两种方式
Jvm-08-garbage collector
阿特拉斯atlas扭矩枪 USB通讯教程基于MTCOM
PyTorch crop images differentiablly
qt使用QZxing生成二维码
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller
Functional modules and application scenarios covered by the productization of user portraits
视觉上位系统设计开发(halcon-winform)
【pytorch学习笔记】Transforms
高并发下之redis锁优化实战
Idea does not specify an output path for the module
XWiki Installation Tips
App global exception capture