当前位置:网站首页>Char array parsing
Char array parsing
2022-06-11 16:52:00 【The most important thing is to persist and never forget the ori】
1、 Statement
Here is an example (=> Express Expression equivalence ):
char a[20] = "abcd";
char b[] = "abcd"; // => char b[5] = "abcd";
const char c[] = "abcd";
char *d = "abcd"; // => const char d[] = "abcd";
const char *e = "abcd"; // => const char e[] = "abcd";
char *f = a + 1; // The pointer f Point to a[1]
const char *g = b; // Fixed pointer g Point to b[0]
char *h = f; // The pointer h And f Point to the same address 2、 Characters and character string
2.1 char character
char Is the character , It's also 0~127 Of unsigned integers . Usually you can use one char The expression is called ASCII code .
String is based on NULL Consecutive addresses at the end . Escape characters are often used in daily life '\0' Express .
For the study of character and string characteristics, please refer to :Link Uploading … Re upload cancel
2.2 char [] It's an array
Here we talk about arrays , It is necessary to know the relationship with the pointer .
Basic knowledge : The array name itself is a pointer , Point to the starting element of the array .
The compiler is processing something like a[i] Of expression when , Convert this expression to *(a + i) In the form of , Then calculate the pointing address of the expression .( This is also C/C++ Subscript from 0 The reason for the beginning , Represents the offset from the header address .)
thus , Can explain :
Use
scanf("%s", str)sentence , There is no need to add an address character to a string , becausestrItself representsstr[]The address of ;Use
sort(a + 1, a + n + 1)sentence ,a + 1anda[1]It is the same after compilation , A fellowa[1]The address of .
2.3 char * And char [] The difference between
char * It's essentially a pointer ;char [] It's essentially an array .
special :
char *a = "abcd"; // (1)
char a[20] = "abcd"; // (2)
The string that appears in the source code ( use "" What's included ) All strings Constant .(1) A pointer to a string constant "abcd" First character ;(2) The string constant is copied into the character array . obviously The former cannot be modified , The latter can be modified .
For detailed differences, please refer to this article :Link Uploading … Re upload cancel
3、 <cstring> library
It is recommended to use the shortcut keys together
Control + F.
3.1 String manipulation #include <cstring>
strcpy(p, p1)Copy string
strncpy(p, p1, n)Copies the specified length string
strcat(p, p1)Additional string
strncat(p, p1, n)Attach the specified length string
strlen(p)Take the string length
strcmp(p, p1)Compare strings
strcasecmpIgnore case comparison strings
strncmp(p, p1, n)Compare a specified length string
strchr(p, c)Find the specified character in a string
strrchr(p, c)Looking backward in a string
strstr(p, p1)Find string
strpbrk(p, p1)Take all the characters of the target string as a set , Find any element of the collection in the current string
strspn(p, p1)Take all the characters of the target string as a set , Find the offset of any element that does not belong to the collection in the current string
strcspn(p, p1)Take all the characters of the target string as a set , Find the offset of any element that belongs to the collection in the current string
- The string handler with the specified length fills the zero terminator after the processed string
3.2 String to numeric conversion #include <cstdlib>
strtod(p, ppend)From a string p Medium conversiondoubleType value , And store the subsequent string pointer toppendPoint to thechar*Type storage .
strtol(p, ppend, base)From a string p Medium conversionlongType integer value ,baseExplicitly set the converted integer base , Set to 0 To determine the base number used according to a specific format ,0x,0XPrefix to be interpreted as an integer in hexadecimal format ,0Prefix to be interpreted as an octal format integer
atoi(p)String conversion tointinteger
atof(p)String conversion todoubleSign points
atol(p)String conversion tolonginteger
3.3 Character checking #include <cctype>
isalpha()Check for alphabetic characters
isupper()Check whether it is an uppercase character
islower()Check for lowercase characters
isdigit()Check if it's a number
isxdigit()Check whether it is a valid character represented by hexadecimal digits
isspace()Check whether it is a space type character
iscntrl()Check whether it is a control character
ispunct()Check whether it is punctuation
isalnum()Check for letters and numbers
isprint()Check if it is a printable character
isgraph()Check whether it is a graphic character , Equivalent toisalnum()|ispunct()
3.4 The function prototype
Prototype 1:
strcpy(char destination[], const char source[]);function : The string source Copy to string destination in
routine :
#include <iostream.h> #include <string.h> void main(void) { char str1[10] = { "TsinghuaOK"}; char str2[10] = { "Computer"}; cout <<strcpy(str1,str2)<<endl; }The result of the operation is : Computer
The second string will overwrite all the contents of the first string !
Be careful : When defining an array , A character array 1 The string length of must be greater than or equal to the string 2 String length of . You cannot assign a string constant or a character array directly to a character array with an assignment statement . All string handling functions are contained in the header file string.h in .
Prototype 2:
strncpy(char destination[], const char source[], int numchars);function : The string source Middle front numchars Copy characters to string destination in
routine :
#include <iostream.h> #include <string.h> void main(void) { char str1[10] = { "Tsinghua "}; char str2[10] = { "Computer"}; cout <<strncpy(str1,str2,3)<<endl; }Running results :Comnghua
Be careful : character string source Middle front numchars Characters will overwrite character string destination Middle front numchars Characters !
Prototype 3:
strcat(char target[], const char source[]);function : The string source Received string target Behind
routine :
#include <iostream.h> #include <string.h> void main(void) { char str1[] = { "Tsinghua "}; char str2[] = { "Computer"}; cout <<strcpy(str1,str2)<<endl; }Running results :Tsinghua Computer
Be careful : When defining a character array 1 The length of the character array should be considered 2 The length of , Because the length of the new string after connection is the sum of the two string lengths . After string connection , character string 1 The terminator of will be automatically removed , At the end of the ending string, keep an ending character after the new string .
Prototype 4:
strncat(char target[], const char source[], int numchars);function : The string source Before numchars Characters to string target Behind
routine :
#include <iostream.h> #include <string.h> void main(void) { char str1[] = { "Tsinghua "}; char str2[] = { "Computer"}; cout <<strncat(str1,str2,3)<<endl; }Running results :Tsinghua Com
Prototype 5:
int strcmp(const char firststring[], const char secondstring);function : Compare two strings firststring and secondstring
routine :
#include <iostream.h> #include <string.h> void main(void) { char buf1[] = "aaa"; char buf2[] = "bbb"; char buf3[] = "ccc"; int ptr; ptr = strcmp(buf2,buf1); if(ptr > 0) cout <<"Buffer 2 is greater than buffer 1"<<endl; else cout <<"Buffer 2 is less than buffer 1"<<endl; ptr = strcmp(buf2,buf3); if(ptr > 0) cout <<"Buffer 2 is greater than buffer 3"<<endl; else cout <<"Buffer 2 is less than buffer 3"<<endl; }The result of the operation is :
Buffer 2 is less than buffer 1
Buffer 2 is greater than buffer 3Prototype 6:
strlen(const char string[]);function : Statistics string string The number of characters in
routine :
#include <iostream.h> #include <string.h> void main(void) { char str[100]; cout <<" Please enter a string :"; cin >>str; cout <<"The length of the string is :"<<strlen(str)<<" individual "<<endl; }Running results :
The length of the string is x(x The total number of characters entered for you )Be careful :strlen The function calculates the actual length of a string , barring '\0' , . in addition ,strlen Function can also directly test the length of string constants , Such as :
strlen("Welcome").7、
void *memset(void *dest, int c, size_t count);take dest front count Characters Set as character c, return dest Value .
8、
void *memmove(void *dest, const void *src, size_t count);from src Copy count Byte characters to dest. If src and dest Overlap , The function automatically handles . return dest Value .
9、
void *memcpy(void *dest, const void *src, size_t count);from src Copy count Byte characters to dest. And memmove Function as , Just can't handle src and dest Overlap . return dest Value .
10、
void *memchr(const void *buf, int c, size_t count);stay buf front count Find first occurrence character in bytes c The location of . Characters found c Or have searched count Bytes , Find and stop . Returned if the operation is successful buf First time in c Position pointer of , Otherwise return to NULL.
11、
void *_memccpy(void *dest, const void *src, int c, size_t count);from src Copy 0 Characters of one or more bytes to dest. When character c Be copied or count When characters are copied , Replication stopped .
If the characters c Be copied , Function returns a pointer to the next character position after this character . Otherwise return to NULL.
12、
int memcmp(const void *buf1, const void *buf2, size_t count);Compare buf1 and buf2 front count Byte size .
Return value < 0, Express buf1 Less than buf2;
The return value is 0, Express buf1 be equal to buf2;
Return value > 0, Express buf1 Greater than buf2.
13、
int memicmp(const void *buf1, const void *buf2, size_t count);Compare buf1 and buf2 front count Bytes . And memcmp The difference is , It's case insensitive .
The return value is the same as above .
14、
char *strrev(char *string);The string string The order of the characters in is reversed . NULL The ending position remains unchanged . Returns a pointer to the adjusted string .
strrev The function is not C++ Standard functions , stay gcc There is no..., defined in the compiler . An alternative ( Yes BUG):
char* strrev(char* s) { /* h Point to s The head of */ char* h = s; char* t = s; char ch; /* t Point to s Tail of */ while (*t++); t--;/* And t++ offset */ t--;/* Jump back over the Terminator '\0' */ /* When h and t When not coincident , Swap the characters they point to */ while (h < t) { ch = *h; *h++ = *t; /* h Move to the tail */ *t-- = ch; /* t Move to the head */ } return (s); }The code comes from :Link Uploading … Re upload cancel
15、
char *_strupr(char *string);take string Replace all lower case letters with corresponding upper case letters , Other characters remain unchanged . Returns a pointer to the adjusted string .
16、
char *_strlwr(char *string);take string Replace all upper case letters with corresponding lower case letters , Other characters remain unchanged . Returns a pointer to the adjusted string .
17、
char *strchr(const char *string, int c);Find word strand string The first place in , NULL The terminator is also included in the lookup . Return a pointer , Pointing character c In string string The first place in , If not found , Then return to NULL.
18、
char *strrchr(const char *string, int c);strrchr() Function lookup character The position of the first occurrence starting from the end in the specified string , If it works , All characters from this position to the end of the string are returned , If you fail , Then return to false. In contrast to this strstr() function , It finds the position in the string where the specified character first appears .
Example
1
2
3
<?php
echostrrchr('Hello world!','world');
?>Output : world!
1
2
3
<?php
echostrrchr('Helloworld.women!','.');
?>Output : women!
19、
strstr()Return a pointer , Pointing character c In string string The last place in , If not found , Then return to NULL.
char *strstr(const char *string, const char *strSearch);In string string Search for strSearch Substring . Returns the substring strSearch stay string Pointer to the first occurrence position in . If no substring is found strSearch, Then return to NULL. If the substring strSearch For the empty string , The function returns string value .
Example :
1
2
3
charstr[]="1234xyz";
char*str1=strstr(str,"34");
cout << str1 << endl;It is shown that : 34xyz
20、
char *strdup(const char *strSource);When the function is running, it will call itself malloc The function is copy strSource String allocates storage space , And then strSource Copy to the allocated space . Pay attention to releasing the allocated space in time .
Return a pointer , Points to the space allocated for the copy string ; If space allocation fails , Then return to NULL value .
char *strcat(char *strDestination, const char *strSource);Put the source string strSource Add to target string strDestination Back , And add... After the new string NULL Terminator . The source string strSource The character of will overwrite the target string strDestination The following Terminator NULL. There is no overflow check in the process of copying or adding strings , Therefore, ensure that the target string space is large enough . Cannot handle the case where the source string overlaps with the target string . The function returns strDestination value .
char *strncat(char *strDestination, const char *strSource, size_t count);Put the source string strSource At the beginning count Characters are added to the target string strDest after . The source string strSource The character of will overwrite the target string strDestination The following Terminator NULL. If count Greater than source string length , Will be replaced by the length value of the source string count value . The new string will be automatically followed by NULL Terminator . And strcat The function is the same , This function cannot handle the case that the source string overlaps with the target string . The function returns strDestination value .
char *strcpy(char *strDestination, const char *strSource);Copy source string strSource To the target string strDestination The designated location , contain NULL Terminator . Cannot handle the case where the source string overlaps with the target string . The function returns strDestination value .
char *strncpy(char *strDestination, const char *strSource, size_t count);Put the source string strSource At the beginning count Characters are copied to the target string strDestination The designated location . If count The value is less than or equal to strSource The length of the string , It doesn't automatically add NULL Terminator in target string , and count Greater than strSource The length of the string , Will strSource use NULL The terminator is filled in count Characters , Copy to target string . Cannot handle the case where the source string overlaps with the target string . The function returns strDestination value .
char *strset(char *string, int c);take string All characters of the string are set to characters c, encounter NULL The terminator stops . Function returns the adjusted string The pointer .
char *strnset(char *string, int c, size_t count);take string The string starts count Characters set as characters c, If count Greater than string The length of the string , Will use string Length replacement of count value . Function returns the adjusted string The pointer .
size_t strspn(const char *string, const char *strCharSet);Find any one that is not included in strCharSet Characters in string ( String Terminator NULL With the exception of ) stay string The sequence number of the first position in the string . Returns an integer value , Specified in the string All of them are characters The length of the substring composed of characters in . If string With a not included in strCharSet The beginning of a character in , Function will return 0 value .
size_t strcspn(const char *string, const char *strCharSet);lookup strCharSet Any character in the string is in string The sequence number of the first position in the string , Contains the string terminator NULL.
Returns an integer value , Specified in the string In all by non characters The length of the substring composed of characters in . If string With a contained in strCharSet The beginning of a character in , Function will return 0 value .
char *strspnp(const char *string, const char *strCharSet);Find any one that is not included in strCharSet Characters in string ( String Terminator NULL With the exception of ) stay string The first position pointer in the string . Return a pointer , Pointing to non strCharSet Characters in string The first place in .
char *strpbrk(const char *string, const char *strCharSet);lookup strCharSet Any character in the string is in string The position of the first occurrence in the string , Does not contain a string Terminator NULL.
Return a pointer , Point to strCharSet Any character in string The first place in . If two string parameters do not contain the same characters , Then return to NULL value .
int strcmp(const char *string1, const char *string2);Compare strings string1 and string2 size .
Return value < 0, Express string1 Less than string2;
The return value is 0, Express string1 be equal to string2;
Return value > 0, Express string1 Greater than string2.
int stricmp(const char *string1, const char *string2);Compare strings string1 and string2 size , and strcmp Different , Compare their lowercase versions . Return value and strcmp identical .
int strcmpi(const char *string1, const char *string2);Equivalent to stricmp function , Just provide a backward compatible version .
int strncmp(const char *string1, const char *string2, size_t count);Compare strings string1 and string2 size , Just compare the front count Characters . In the process of comparison , The length of any string is less than count, be count Will be replaced by a shorter string length . In this case, if the characters before the two strings are equal , The shorter string is smaller .
Return value < 0, Express string1 The substring of is less than string2 The string of ;
The return value is 0, Express string1 The substring of is equal to string2 The string of ;
Return value > 0, Express string1 The substring of is greater than string2 The string of .
int strnicmp(const char *string1, const char *string2, size_t count);Compare strings string1 and string2 size , Just compare the front count Characters . And strncmp The difference is , Compare their lowercase versions . Return value and strncmp identical .
char *strtok(char *strToken, const char *strDelimit);stay strToken Find the next tag in the string , strDelimit The character set specifies the delimiters that may be encountered in the current lookup call . Return a pointer , Point at strToken Next tag found in . If the tag is not found , Just go back to NULL value . Each call modifies strToken Content , use NULL Every delimiter encountered by character substitution .
边栏推荐
- Differences between list and set access elements
- 【pytest学习】pytest 用例执行失败后其他不再执行
- Is the securities account given by qiniu business school safe? Do you charge for opening an account
- How unittest knows the execution time of each test case
- How to disable the notebook's own keyboard after the notebook is connected to an external keyboard
- 二级造价工程师值得考吗?发展前景如何?
- LeetCode——24. 两两交换链表中的节点(三指针)
- 啟牛商學院給的證券賬戶是安全的嗎?開戶收費嗎
- 虚拟局域网划分与虚拟局域网间路由(VLAN)
- pycharm和anaconda的基础上解决Jupyter连接不上Kernel(内核)的问题--解决方案1
猜你喜欢

Elasitcsearch basic learning notes (1)

信息收集常用工具及命令

Katalon Studio Enterprise

Why does chip design also need "Craftsmanship"?

JINTE NET基金会将通过线上直播参与维度链全球战略发布会

How unittest knows the execution time of each test case

Leetcode 1974. 使用特殊打字机键入单词的最少时间(可以,一次过)

2022年高处安装、维护、拆除考试模拟100题及在线模拟考试

^32 execution context stack interview questions

Go语言之Go 快速入门篇(一):第一个 Go 程序
随机推荐
Web page design example assignment -- Introduction to Henan cuisine (4 pages) web final assignment design web page_ Dessert and gourmet college students' web design homework finished product
2022年高处安装、维护、拆除考试模拟100题及在线模拟考试
一套ThinkPHP微信小程序商城源码带后台管理
Web security - shooting range notes
A journey of database full SQL analysis and audit system performance optimization
Katalon Studio Enterprise
Intranet penetration based on UDP port guessing
7个人生工具:SWOT、PDCA、6W2H、SMART、WBS、时间管理、二八原则
项目无法加载nacos配置中心的配置文件问题
Difference between select into from and insert into select
Redis --- 学习 NoSQL 五大类型
Leetcode 1974. Minimum time to type words using a special typewriter (yes, once)
“is-a”,“has-a”,“like-a”
CS0006 C# 未能找到元数据文件“C:\Users\...问题
Pychart tips - how to set up a background picture
Oracle generates non duplicate string sys_ Guid() and MySQL generate unique values
The micro service failed to connect to the cloud sentinel console and the link blank problem occurred after the connection was successful (resolved)
jsp页面初始加载方式
CLP Jinxin helps Rizhao bank put into operation its new financial ecological network
Project failed to load the configuration file of Nacos configuration center