当前位置:网站首页>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 .

边栏推荐
- socket.io搭建分布式Web推送服务器
- [pytorch learning notes] datasets and dataloaders
- [probably the most complete in Chinese] pushgateway entry notes
- Tensorflow realizes verification code recognition (III)
- Relationship between truncated random distribution and original distribution
- Visual upper system design and development (Halcon WinForm) -2 Global variable design
- Chapter 04_ Logical architecture
- Search in the two-dimensional array of leetcode sword offer (10)
- What is one hot encoding? In pytoch, there are two ways to turn label into one hot coding
- [cloud native training camp] module VIII kubernetes life cycle management and service discovery
猜你喜欢

秒杀系统1-登录功能

High quality workplace human beings must use software to recommend, and you certainly don't know the last one

高并发下之redis锁优化实战

Halcon与Winform学习第一节

el-switch 赋值后状态不变化

北京共有产权房出租新规实施的租赁案例

Kubernetes 进阶训练营 Pod基础

Redis lock Optimization Practice issued by gaobingfa

Popular understanding of decision tree ID3

Characteristics of MySQL InnoDB storage engine -- Analysis of row lock
随机推荐
socket.io搭建分布式Web推送服务器
Redis lock Optimization Practice issued by gaobingfa
[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention
GCC cannot find the library file after specifying the link library path
Leetcode the smallest number of the rotation array of the offer of the sword (11)
Global and Chinese market of Bus HVAC systems 2022-2028: Research Report on technology, participants, trends, market size and share
Win10 enterprise 2016 long term service activation tutorial
The state does not change after the assignment of El switch
MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller
win32创建窗口及按钮(轻量级)
What is one hot encoding? In pytoch, there are two ways to turn label into one hot coding
Popular understanding of gradient descent
The first character of leetcode sword offer that only appears once (12)
Mysql报错:[ERROR] mysqld: File ‘./mysql-bin.010228‘ not found (Errcode: 2 “No such file or directory“)
详解指针进阶2
[pytorch learning notes] datasets and dataloaders
Global and Chinese markets for infrared solutions (for industrial, civil, national defense and security applications) 2022-2028: Research Report on technology, participants, trends, market size and sh
What is embedding (encoding an object into a low dimensional dense vector), NN in pytorch Principle and application of embedding
Introduction, use and principle of synchronized
