当前位置:网站首页>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/
边栏推荐
- Concurrent programming 1-2
- Fpga:ov7725 camera displays images in rgb565 format through vga/hdmi
- Seektiger's okaleido has a big move. Will the STI of ecological pass break out?
- Form resume
- About redis: there is still a risk of data loss after redis sets data persistence
- Tutorial on principles and applications of database system (043) -- MySQL query (V): Sorting Query Results
- Image processing: Generation 3 × Window of 3
- Redis - basic concept
- How to relieve the pillow quickly
- The winverifytrust call returned 80096005 error. The timestamp signature or certificate cannot be verified or is damaged
猜你喜欢

Sublime text 3 Chinese + add common plug-ins

爬虫请求库的使用2

kubernetes 部署 dashboard(可视化界面)

C language database: detailed description. Use the student management system to understand the operation of the database, which is simple and easy to understand.

Programmeur de cheval noir - test d'interface - test d'interface d'apprentissage de quatre jours - jour 4 - Postman lit des fichiers de données externes, lit des données de fichiers de données, IHRM P

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

Deep understanding of collaborative process

Concept, key points and summary of postgraduate entrance examination in Polymer Physics

docker redis

Fpga:ov7725 camera displays images in rgb565 format through vga/hdmi
随机推荐
Openresty模板实时渲染 lua-resty-template
数仓搭建——ODS层
爬虫requests模块的基本使用
1000 okaleido tiger launched binance NFT, triggering a rush to buy
The problem that all values are the same occurs after golang for range traverses and assigns values to the dictionary
落枕如何快速缓解
Idea compiler sets the separation line between methods
js的相关知识
Static extension configuration
[QNX Hypervisor 2.2用户手册]9 VM配置参考
Tutorial on the principle and application of database system (048) -- MySQL query (x): self connection query
[untitled]
Tutorial on the principle and application of database system (049) -- MySQL query (XI): sub query
scroll-view实现下拉刷新(避免onload进入页面初始refresher-triggered为true触发下拉问题)
C language force deduction question 53 of the largest subarray sum. Dynamic programming and divide and conquer
Sublime text 3 汉化+添加常用插件
Tutorial on principles and applications of database system (047) -- MySQL query (IX): connection query
Modify node temporarily_ Modules package source code and compile reference to modify dependent packages
J'ai choisi la mauvaise technologie au mauvais moment.
Chapter 1 water test --*offer