当前位置:网站首页>Analysis and Simulation of strlen function
Analysis and Simulation of strlen function
2022-07-24 19:31:00 【kunmu.】
️ Function analysis and simulation implementation
List of articles
Function analysis
The function prototype :
size_t strlen (const char* str)The header file : <string.h>
effect (function):Get string length
Translation translation : Get the string at \0 The number of characters before .
Parameters :const char* str
Translation translation : Receive a character pointer .
give an example :
int main() { char str1[] = "abcdef"; // Store the string in the character array char* str = "123456"; //str Is a pointer variable , The address of the first element of the string int len1 = strlen(str1); // The address of the first element of the array name , Pass it on to strlen int len2 = strlen(str); // take str Pass to strlen return 0; }
Return type :size_t( Unsigned integer )
Translation translation : Returns a greater than or equal to 0 The positive integer .
Three methods are simulated strlen
1、 Iterative method implementation strlen
#include<assert.h>
size_t my_strlen(const char* str)
{
assert(str); // Because it needs to be right str To dereference , prevent str by NULL Cause an error
int count = 0;
while(*str++) //'\0' Of ASCLL The code value is 0, Can be used as a loop end condition
{
count++;
}
return count;
}
2、 The pointer — The pointer
The pointer — The pointer : The absolute value of subtracting two pointers is the number of elements between pointers , Premise is : Pointers to the same space can be subtracted
#include<assert.h>
size_t my_strlen(const char* str)
{
assert(str);
char* start = str;
while(*str != '\0')
{
str++; // Make str Found in the \0 Previous address
}
return str - start; // Pointers to the same space are subtracted , Return the number of elements between them
}
3、 Recursive method
#include<assert.h>
size_t my_strlen(const char* str)
{
assert(str);
if(*str != '\0')
{
return 1 + my_strlen(++str); // When str The content pointed to is not '\0' When the , Recursion ,str Point to the next content
}
else
{
return 0;
}
}
matters needing attention
1、 Understanding of return parameters
give an example :
Analyze the following code :
answer :
strlen(arr1) The result must be 3,strlen(arr2) The result must be 4, How can it print out "arr1 > arr2" As a result ?
because strlen The return type of the function is size_t The unsigned integer of , Then the result of subtracting two unsigned integers must also be unsigned integers , That is, the result must be greater than or equal to 0.
So it's using strlen When the result returned by the function compares the length of two strings , Try to use Relational operator Compare .
2、strlen Pay attention to
①:strlen The function calculates \0 The number of characters before , If there is \0, The result of the calculation will end in advance
②:strlen The parameter required by the function is an address , Cannot be constant , It can't be a wild pointer .
边栏推荐
- [Huawei lyevk-3861a intelligent IOT development board evaluation] unpacking experience and Hisilicon hi3861v100 chip learning experience
- Configmanager of unity framework [JSON configuration file reading and writing]
- Detailed explanation of ELF format (I)
- Channel state information (CSI) conjugate multiplication denoising method
- Techempower web framework performance test 21st round results release --asp Net core continue to move forward
- Free and open source website navigation source code collection, sorting and summary - self built personal navigation Homepage
- Create a life cycle aware MVP architecture
- [untitled]
- Integer
- Cesium uses czml to implement dynamic routes
猜你喜欢

Tencent Browser service TBS usage

day 1

On July 31, 2022, the dama-cdga/cdgp data governance certification class was opened!

Rotation matrix derivation process

High speed ASIC packaging trends: integration, SKU and 25g+

文献阅读:GoPose 3D Human Pose Estimation Using WiFi

Sword finger offer 52. The first common node of the two linked lists

Reading notes of XXL job source code

How to encrypt your own program with dongle

Emergency lighting design of large stadiums and gymnasiums
随机推荐
Siyuan notes V2.1.2 synchronization problem
Equals() method of object class
C # shelling tool for code encryption protection
Original reverse compensation and size end
Process pool and fallback function [easy to understand]
JS part
2022 Hangzhou Electric Multi school first Dragon Slayer (dfs+ state compression)
Compressed string
Unity框架之ConfigManager【Json配置文件读写】
Math
LSTM and Gru of RNN_ Attention mechanism
Thread theory knowledge
Mysql database, de duplication, connection
Using videoview to realize video playback in turns
PostgreSQL weekly news - July 13, 2022
Convolutional neural network CNN
Nezha monitoring - server status monitoring, SSL certificate change expiration, Ping monitoring and scheduled task reminder
Mysql8.0 learning record 19 - Page segments and tablespaces
Sword finger offer 45. arrange the array into the smallest number
Sword finger offer 47. the maximum value of gifts
