当前位置:网站首页>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 :
边栏推荐
- 基于线性函数近似的安全强化学习 Safe RL with Linear Function Approximation 翻译 2
- Go context basic introduction
- Servlet基本原理与常见API方法的应用
- VLAN part of switching technology
- Dynamic address book
- View CSDN personal resource download details
- Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
- 【OpenCV 例程200篇】218. 多行倾斜文字水印
- Hands on deep learning (43) -- machine translation and its data construction
- leetcode1229. Schedule the meeting
猜你喜欢
Hands on deep learning (39) -- gating cycle unit Gru
El Table Radio select and hide the select all box
对于程序员来说,伤害力度最大的话。。。
Intelligent gateway helps improve industrial data acquisition and utilization
RHCE day 3
OSPF summary
uniapp 处理过去时间对比现在时间的时间差 如刚刚、几分钟前,几小时前,几个月前
SQL replying to comments
2. Data type
Use the data to tell you where is the most difficult province for the college entrance examination!
随机推荐
【Day1】 deep-learning-basics
Servlet基本原理与常见API方法的应用
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
有老师知道 继承RichSourceFunction自定义读mysql怎么做增量吗?
Uniapp--- initial use of websocket (long link implementation)
Kotlin: collection use
Vanishing numbers
Exercise 9-5 address book sorting (20 points)
Some summaries of the third anniversary of joining Ping An in China
Delayed message center design
Hlk-w801wifi connection
Basic principle of servlet and application of common API methods
A little feeling
Doris / Clickhouse / Hudi, a phased summary in June
【Day2】 convolutional-neural-networks
Native div has editing ability
原生div具有编辑能力
Two way process republication + routing policy
OSPF summary
Occasional pit compiled by idea