当前位置:网站首页>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 :
边栏推荐
- What are the advantages of automation?
- [200 opencv routines] 218 Multi line italic text watermark
- Rhcsa day 9
- Button wizard business running learning - commodity quantity, price reminder, judgment Backpack
- Rhcsa - day 13
- 转载:等比数列的求和公式,及其推导过程
- 2021-08-10 character pointer
- BGP advanced experiment
- 对于程序员来说,伤害力度最大的话。。。
- 【Day2】 convolutional-neural-networks
猜你喜欢
Number of relationship models
Debug:==42==ERROR: AddressSanitizer: heap-buffer-overflow on address
Hands on deep learning (46) -- attention mechanism
leetcode1-3
RHCE - day one
If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
Hands on deep learning (39) -- gating cycle unit Gru
The future education examination system cannot answer questions, and there is no response after clicking on the options, and the answers will not be recorded
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
Rhcsa - day 13
随机推荐
Summary of reasons for web side automation test failure
Vanishing numbers
Devop basic command
5g/4g wireless networking scheme for brand chain stores
PHP code audit 3 - system reload vulnerability
El Table Radio select and hide the select all box
如果不知道這4種緩存模式,敢說懂緩存嗎?
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
Use the data to tell you where is the most difficult province for the college entrance examination!
MySQL develops small mall management system
A little feeling
Map container
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 2
DDL statement of MySQL Foundation
使用 C# 提取 PDF 文件中的所有文字(支持 .NET Core)
PHP代码审计3—系统重装漏洞
Custom type: structure, enumeration, union
What is devsecops? Definitions, processes, frameworks and best practices for 2022
Golang type comparison