当前位置:网站首页>Use and understanding of string functions (2)
Use and understanding of string functions (2)
2022-07-24 01:10:00 【Earnest kitten】
**
Use and understanding of string functions (2)
Here comes the note
After last time, there are :
String function with limited length : 1,strncpy 2,strncat 3,strncmp;
Memory manipulation function :1,memcpy 2,memmove 3,memset 4,memcmp;
String search :1,strstr 2,strtok;
Error message report : strerror
1、 String function with limited length
strncpy The function prototype is :
char * strncpy ( char * destination, const char * source, size_t num );
Glance at , Why ~, Than before strcpy The function prototype has more parameters , Not bad , In fact, relative and no length constraints , Here, you only need to set the number you want to control ( Company : byte ).
Let's give you an example :
char * my_strncpy(char *dest, const char *str,size_t count)
{
assert(dest && str); // Ensure the validity of the pointer ( This is with B Brother Peng of the station learned )
char* ret = dest;
while (count && (*dest++ = *str++))
count--;
if (count)
while (--count)
*dest++ = '\0';
return ret;
}
int main()
{
char arr1[10] = "hello";
char arr2[] = "world";
// strncpy(arr1, arr2,4); // The third parameter is the number of bytes ,arr1 Is the source string ; When arr2 The specified number is much larger than the string "world" a long time , Make up automatically ‘\0’
// If the length of the source string is less than num, After copying the source string , Append... After the target 0, until num individual
my_strncpy(arr1, arr2,4); // Custom implementation function
printf("%s\n", arr1);
return 0;
});
Compared with the previous one , In fact, they are roughly the same format , It's just , When operating a string, it is almost the same as what is implied behind the string ‘\0’ Dealing with .
I won't say much about the last two , Direct example :
strncat String append prototype :
char * strncat ( char * destination, const char * source, size_t num );
Custom implementation function :
char * my_strncat(char *dest, const char *str,size_t count)
{
assert(dest && str);
char* ret = dest;
while (*dest++)
;
dest--;
while (count--)
if(!(*dest++ = *str++))
return ret;
*dest = '\0';
return ret;
}
int main()
{
char arr1[20] = "hello\0abcd";
char arr2[] = "world";
//strncat(arr1, arr2,4); // The third parameter is the number of strings appended ,arr1 Is the source string ;arr2 Additional 4 A string , Not more than "world" Length of string , Only in arr1 Of \0 After add 4 The first string is :"helloworl",
// If the number of appendages exceeds the string arr2 The number of , Only all strings "world" Add the past ( belt \0), No more superfluous \0
my_strncat(arr1, arr2,4); // Custom function
printf("%s\n", arr1);
return 0;
}
strncmp String comparison ,ASCII Value size comparison ;
The prototype function is
int strncmp ( const char * str1, const char * str2, size_t num );
Find for string :
------------------------strstr Find string -------------------------------------
// Prototype :const char * strstr ( const char * str1, const char * str2 );
char * strstr(char * str1, const char * str2);
// This example is in the str Mid search “simple” Substring and replace it with “sample”.
int main ()
{
char str[] = "This is a simple string";
char * pch;
pch = strstr(str, "simple");
if (pch != NULL)
strncpy(pch, "sample", 6);
printf("%s\n",str); // Output This is a sample string
return 0;
}
About memory operation functions :
----------------------memcpy Memory copy --------------------------------
// Prototype :void * memcpy ( void * destination, const void * source, size_t num ); The third parameter is to set how many bytes to copy
// Implement a memory copy function by yourself
struct s
{
char name[20];
int age;
};
void * my_memcpy(void * destination, const void * source, size_t num)
{
assert(destination && source);
char* ret = destination;
while (num--)
{
*(char*)destination = *(char*)source;
++(char*)destination; // First line data conversion , Again ++
++(char*)source;
}
return ret;
}
int main()
{
struct s arr1[] = {
{
"zhangsan",20},{
"lisi",30} };
struct s arr2[4] = {
0 };
my_memcpy(arr2, arr1, sizeof(arr1)); // take arr1 The contents are completely copied to arr2 In the middle .
return 0;
}
It should be noted that :C Language policy memcpy As long as the memory is not overlapped ,
memmove Function to handle the copy of memory overlap .
Define your own memmove function :
void * my_memcpy(void * destination, const void * source, size_t num)
{
char* ret = destination;
assert(destination && source);
if (destination < source)
{
// From before to after
while (num--)
{
*(char*)destination = *(char*)source;
++(char*)destination; // First line data conversion , Again ++
++(char*)source;
}
}
else
{
// From back to front
while (num--)
*((char*)destination +num) = *((char*)source+num);
}
return ret;
}
memset// Memory settings , This function It is used to fill a given value in a block of memory . Because it can only fill in one value , So the initialization of this function is the original initialization , Unable to initialize variable to data needed in program . use memset After initialization , Later, the program will store the required data in the memory space . The unit of change is bytes
example :
int main()
{
int arr[10] = {
0 };
memset(arr,'#',10);// take arr Array of 10 Change bytes into characters '#'
int arr1[10] = {
0 };
memset(arr1, 1, 10); // This is easy to make mistakes , the reason being that int An array of types , And this sentence only changed the former 10 Bytes , But the whole array has 40 Bytes , In fact, it is only changed to :
//01 01 01 01 01 01 01 01 01 00 00 ( The first two int type ).....00
return 0;
}
For these functions , In fact, I just want to know how to use it , Just find the rules for using functions , There are a lot of them on the Internet . But I want to write a custom function by myself , Then we need to fully understand this function , And certain thinking ability , Of course , There are also lower versions VS compiler , The source code is provided , however VS17 It's hard to find the source code .
Refer to the following website for these functions ~:
http://www.cplusplus.com/
边栏推荐
- WinVerifyTrust调用返回80096005错误,时间戳签名或证书无法验证或已损坏
- Description of TCP packet sticking problem code
- Tutorial on principles and applications of database system (051) -- MySQL query (XIII): using queries in DML statements
- Intelligent video monitoring solutions for elderly care institutions, using new technologies to help the intelligent supervision of nursing homes
- Modify node temporarily_ Modules package source code and compile reference to modify dependent packages
- Easyexcel export case (only you can't think of it)
- [flyway introduction]
- Okaleido tiger NFT is about to log in to the binance NFT platform. Are you looking forward to it?
- 【FreeSwitch开发实践】专栏简介
- 对皮尔逊相关系数进行假设检验
猜你喜欢

复现一句话木马

Testers who have been employed for 3 months are facing employment confirmation. Leaders: 1 year of work experience is packaged into 5 years, and the probation period is eliminated

Analysis of the advantages of the LAAS scheme of elephant swap led to strong performance of ETOKEN

ACL——net

B tree and b+ tree

项目场景:nvidia-smi Unable to datemine the device handle for GPU 0000:01:00.0: Unknow Error

The salary of a tester who has worked for 3 years after job hopping is twice that of the original. The secret is

HCIP第六天_特殊区域综合实验

OSI open system interconnection model and tcp/ip model

Dark horse programmer - interface test - four day learning interface test - day 4 - postman reads external data files, reads data files, IHRM project practice, employee management module, adds employe
随机推荐
JS related knowledge
The flare project celery uses the pits encountered in redis sentinel
Graphic pipeline (I) post-processing stage alpha test template test depth test mix
For data security reasons, the Dutch Ministry of Education asked schools to suspend the use of Chrome browser
Solve the problem that MySQL inserts Chinese garbled code into the table
Establishment of static route
Focus on microservices
数仓搭建——ODS层
Group chat room based on UDP
Centernet target detection model and centerfusion fusion target detection model
Idea compiler sets the separation line between methods
Scroll view realizes drop-down refresh (to avoid the drop-down problem triggered by the initial refresh triggered value of true when onload enters the page)
Tutorial on the principle and application of database system (049) -- MySQL query (XI): sub query
The problem that all values are the same occurs after golang for range traverses and assigns values to the dictionary
[untitled]
项目场景:nvidia-smi Unable to datemine the device handle for GPU 0000:01:00.0: Unknow Error
[reply] about the fact that I chose the wrong technology at the wrong time
[freeswitch development practice] column introduction
Understand the locks that can't
cnpm 执行时卡住应该怎么解决?