当前位置:网站首页>Collection of practical string functions
Collection of practical string functions
2022-07-04 10:25:00 【sqjddb】
String function
>> Find the string length
strlen
String to ‘\0’ As an end sign ,strlen Function returns in a string ‘\0’ The number of characters that appear before ( It doesn't contain ‘\0’ )
The string that the argument points to must be in ‘\0’ end
Note that the return value of the function is size_t, It's unsigned
Classic examples ( Fallible ):
#include <stdio.h>
int main()
{
const char*str1 = "abcdef";
const char*str2 = "bbb";
if(strlen(str2)-strlen(str1)>0)
{
printf("str2>str1\n");
}
else
{
printf("srt1>str2\n");
}
return 0;
}
because strlen The return value is size_t type , therefore strlen(str2)-strlen(str1) It's also size_t type , Must be greater than zero
strlen Simulation Implementation of
List three ways
The way 1:
// Counter mode
int my_strlen(const char * str)
{
int count = 0;
while(*str)
{
count++;
str++;
}
return count;
}
The way 2:
// Cannot create temporary variable counter
int my_strlen(const char * str)
{
if(*str == '\0')
return 0;
else
return 1+my_strlen(str+1);
}
The way 3:
// The pointer - The way of the pointer
int my_strlen(char *s)
{
char *p = s;
while(*p != ‘\0’ )
p++;
return p-s;
}
>> Unlimited length string function
strcpy ( Copy string )
The source string must be in ‘\0’ end
In the source string ‘\0’ Copy to target space
The target space has to be variable , So the source string cannot be copied into the constant string
The target space has to be large enough , To ensure that the source string can be stored
strcpy Simulation Implementation of :
char *my_strcpy(char *dest, const char*src)
{
char *ret = dest;
assert(dest != NULL);
assert(src != NULL);
while((*dest++ = *src++))
{
;
}
return ret;
}
strcat ( Append string )
The source string must be in ’\0’ end
The target space has to be large enough , It can accommodate the source string
In the source string ‘\0’ Copy to target space
The target space must be modifiable
String cannot be used behind itself strcat Additional , Because first put the... Of the target string ’\0’ Cover , There is no in the string ’\0’, There will be mistakes
strcat Simulation Implementation of :
char *my_strcat(char *dest, const char*src)
{
char *ret = dest;
assert(dest != NULL);
assert(src != NULL);
while(*dest)
{
dest++;
}
while((*dest++ = *src++))
{
;
}
return ret;
}
strcmp ( Compare strings )
The first string is larger than the second string , Return greater than 0 The number of
The first string is equal to the second string , Then return to 0
The first string is less than the second string , Then return less than 0 The number of
strcmp Simulation Implementation of :
clever , Worthy of taste
int my_strcmp (const char * src, const char * dst)
{
assert(src != NULL);
assert(dest != NULL);
while( *src == *dst)
{
if(*str=='\0')
return 0;
++src;
++dst;
}
return( *scr-*dst);
}
>> String function with limited length
The use method is similar to the string function with unlimited length , Just specify a length , Some special requirements can be achieved , It is also safer
strncpy ( Copy the specified characters to the target space )
If the length of the source string is less than count, After copying the source string , Add... After the target 0, until count individual
strncpy Implementation method in the Library :
strncat ( Append the specified characters to the target space )
After addition , Add one more ’\0’
If the number of characters in the source string is less than count, After appending the source string , Just one more ’\0’
strncat Implementation method in the Library :
strncmp ( Compare the specified number of characters )
strncmp The implementation in the library is somewhat complicated :
>> String search
strstr ( Find the string in the string )
strstr The implementation of the :
char *my_strstr(const char* str1, const char* str2 )
{
assert(str1);
assert(str2);
char *cp = NULL; // Point to str1 China and str2 The starting position of the comparison
char *s1 = NULL; // Point to str1 Characters being compared in
char *s2 = NULL; // Point to str Characters being compared in
if(*str2 == '\0')
return((char *)str1); // This is handled in the library function
while(*cp)
{
s1 = cp;
s2 = str2;
while(*s1 && *s2 && (*s1 == *s2))
{
s1++;
s2++;
}
if(*substr == '\0')
return cp;
cp++;
}
}
>> String segmentation
strtok ( Divide the string according to the specified character )
strDelimit Points to a collection of defined delimiters
The first parameter specifies a string , It contains 0 One or more specified delimiters
strtok Function found str Next separator in , Replace with \0 , Return a pointer to this position . ( notes :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 separator in the ,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 separator
If there are no more tags in the string , Then return to NULL The pointer
Examples of use : use @ and . Split mailbox "[email protected]"
#include <stdio.h>
int main()
{
char *p = "[email protected]";
const char* sep = "[email protected]"; // Specify the separator as '.' and '@'
char arr[30];
char *str = NULL;
strcpy(arr, p);// Make a copy of the data , Handle arr Contents of array
for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep))
{
printf("%s\n", str);
}
}
Running results :
>> Error message report
strerror ( Return the error information corresponding to the error code )
When there is an error in the program , Error labels are stored in variables errno( Standard error number , It's defined in errno.h in ), hold errno Pass to strerror function , Will return an error message
For example, open a file that does not exist :
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE * pFile;
pFile = fopen("unexist.txt", "r");
if (pFile == NULL)
printf("%s\n", strerror(errno));
//errno: Last error number
return 0;
}
Running results :
边栏推荐
- Rhcsa learning practice
- Dynamic memory management
- leetcode1-3
- Latex arranges single column table pictures in double column format articles
- 【Day1】 deep-learning-basics
- Leetcode48. Rotate image
- Native div has editing ability
- Sword finger offer 31 Stack push in and pop-up sequence
- Hands on deep learning (43) -- machine translation and its data construction
- DCL statement of MySQL Foundation
猜你喜欢
【OpenCV 例程200篇】218. 多行倾斜文字水印
【Day2】 convolutional-neural-networks
Hands on deep learning (45) -- bundle search
Intelligent gateway helps improve industrial data acquisition and utilization
Normal vector point cloud rotation
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
【Day1】 deep-learning-basics
Online troubleshooting
How can Huawei online match improve the success rate of player matching
What are the advantages of automation?
随机推荐
Tables in the thesis of latex learning
PHP code audit 3 - system reload vulnerability
Es entry series - 6 document relevance and sorting
Introduction to extensible system architecture
Check 15 developer tools of Alibaba
Reasons and solutions for the 8-hour difference in mongodb data date display
Hands on deep learning (III) -- Torch Operation (sorting out documents in detail)
Kotlin: collection use
Hands on deep learning (40) -- short and long term memory network (LSTM)
Kotlin set operation summary
How can Huawei online match improve the success rate of player matching
RHCE - day one
5g/4g wireless networking scheme for brand chain stores
DML statement of MySQL Foundation
From programmers to large-scale distributed architects, where are you (I)
Use the data to tell you where is the most difficult province for the college entrance examination!
Application of safety monitoring in zhizhilu Denggan reservoir area
View CSDN personal resource download details
Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing
Container cloud notes