当前位置:网站首页>Detailed explanation of string function and string function with unlimited length
Detailed explanation of string function and string function with unlimited length
2022-07-03 15:23:00 【Little snail rushes towards】
Preface
author : Little snail rushes forward
quotes : I can accept failure , But I can't accept giving up
If you think the blogger's article is good , Please
give the thumbs-up , Collection , Follow and support bloggers . If you find any problems, you are welcome * Please make corrections in the comments section .
This blog mainly introduces some string function implementations and points for attention .
Find the string length
strlen function
Definition
![]()
The ginseng

Pass string In the past or The first address of the string .
This function is used to find the length of the string , encounter '\0' Just stop counting , The return type is size_t(unsigned int ),
The header file is <string.h>, Next we will continue to introduce how to use .
strlen Use examples :
#include<stdio.h>
#include<string.h>
int main()
{
char arr []= "abcdef";
int ret = strlen(arr);
printf("ret = %d\n", ret);
return 0;
}
It is also possible to directly transmit strings here .

We know strlen Use of functions , In order to let us better understand strlen function . Next, I will use three ways to simulate the implementation strlen function .
1 The way of the counter
// Counter implementation
size_t my_strlen(const char* str)
{
assert(str);// The assertion string is not an empty string
int count = 0;// Record the number of characters
while (*str != '\0')
{
count++;
str++;
}
return count;
}2 Recursive implementation
size_t my_strlen_1(const char* str)
{
assert(str);// The assertion string is not an empty string
if (*str != '\0')
{
return 1 + my_strlen_1(str + 1);
}
else
{
return 0;
}
}3 The pointer - Pointer implementation
// The pointer - Pointer implementation
int my_strlen(const char* str)
{
assert(str);// The assertion string is not an empty string
char* start = str;// take arr The address to start
char* end = str;//arr Address to end
while (*end != '\0')
{
// If *end It's not equal to '\0'
end++;// The pointer ++
}
return end - start;// The pointer - The pointer is equal to the length
}We know strlen How to calculate the string , What should we pay attention to when using this function ?
Be careful :
String is based on '\0' As a sign of the end ,strlen Is a statistical string '\0' Previous characters .
The string that the argument points to must be in '\0' end .
The return type of the string is size_t type .
Unlimited length string function
strcpy String copy function
strcat String append function
strcmp String comparison function
strcpy String copy function
Definition

Parameters

strcpy( Target string , The source string );
strcpy Is a string copy function , It can copy the source string into the target string ,
The return type is char*( The return is the address at the beginning of the target string ),
The header file is <string.h>.
strcpy Use examples :
int main()
{
char arr1[20] = "abcdefg" ;
char arr2[] = "ping";
strcpy(arr1, arr2);// Copy string
printf("%s\n", arr1);
return 0;
}
What we should pay attention to here is strcpy Not just arr2 Copy the characters in , Also put '\0' Copy it .

Simulation Implementation strcpy
char* my_strcpy(char* dest, const char* source)
{
assert(dest && source);// Assertion
char* ret = dest;// Save the first address of the target string
while (*dest++ = *source++)
{
;
}
return ret;
}strcpy Function note :
The source string must be in '\0' end .
In the source string '\0' Copy to target space .
The target space has to be large enough , To ensure that the source string can be stored .
The target space has to be variable .
strcat String append function
Definition
![]()
Parameters

strcat( Target string , The source string );
strcat Is a string appending function , To be able to The characters of the source string are appended to the destination string .
The return type is char*( The return is the address at the beginning of the target string ),
The header file is <string.h>.
strcat Use examples :
int main()
{
char arr1[20] = "allow";
char arr2[] = "act";
strcat(arr1, arr2);// Append string
printf("%s\n", arr1);
return 0;
}
strcat Simulation Implementation
char* my_strcat(char* dest, const char* scoure)
{
assert(dest && scoure);// Assertion
char* ret = dest;
// Find the destination string '\0'
while (*dest!=NULL)// Don't use it here (*dest++) This will cause skipping '\0'
{
dest++;
}
// Append string
while (*dest++ = *scoure++)
{
;
}
return ret;
}Be careful :strcat function
The source string must be in '\0' end .
The target space must be large enough , It can hold the contents of the source string .
The target space must be modifiable .
You can't append strings to yourself , The program will crash .
strcmp String comparison function
Definition

Parameters

strcmp(string1,string2);
Return value

strcmp Is a string comparison function , This function starts with the elements of two strings , Compare ( The essence of comparison is letters ascii The size of the code value ).
The header file is <string.h>.
strcmp Use examples :
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
\
int main()
{
char* p1 = "abcdef";
char* p2 = "afe";
int ret = strcmp(p1, p2);
if (ret > 0)
{
printf(" Constant string p1 Greater than constant string p2\n");
}
else if (ret < 0)
{
printf(" Constant string p1 Less than constant string p2\n");
}
else
{
printf(" Constant string p1 Equal to constant string p2\n");
}
return 0;
}
Many people here may have questions , How is a string p1< character string p2, Mingming string p1 Yes 6 Characters and strings p2 Only 3 Characters .
Here we have to distinguish strcmp The function does not compare the number of characters in a string , With p1 and p2 give an example , Compare first p1 Medium a and p2 Medium a It is found that the two are equal , Just continue to compare ,b and f Size , Obviously f It's better than b Big , therefore strcmp Just return to a less than 0 Number of numbers .
We continue simulation First strcmp function Deepen the understanding
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);// Assertion
while (*str1== *str2)
{
// Judge str1 and str2 Whether it is equal or not
if (*str1 == '\0')// When str1==str2
{
return 0;
}
str1++;
str2++;
}
//str1 And str2 It's not equal , Compare the size
return (*str1 - *str2);
}strcmp function
Be careful :
Understand well strcmp Comparison method , It is convenient for us to use it correctly strcmp function .
If you like, please point a compliment and go !

边栏推荐
- Tensorflow realizes verification code recognition (I)
- 视觉上位系统设计开发(halcon-winform)-4.通信管理
- CString中使用百分号
- 函数栈帧的创建和销毁
- Jvm-03-runtime data area PC, stack, local method stack
- Functional modules and application scenarios covered by the productization of user portraits
- Concurrency-02-visibility, atomicity, orderliness, volatile, CAS, atomic class, unsafe
- Matplotlib drawing label cannot display Chinese problems
- 从 flask 服务端代码自动生成客户端代码 -- flask-native-stubs 库介绍
- win32创建窗口及按钮(轻量级)
猜你喜欢

运维体系的构建

Kubernetes 进阶训练营 Pod基础
![[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention](/img/94/a9c7010fe9f14454469609ac4dd871.png)
[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention

Visual host system design and development (Halcon WinForm)

视觉上位系统设计开发(halcon-winform)-3.图像控件

WinDbg分析dump文件

视觉上位系统设计开发(halcon-winform)-1.流程节点设计

Digital image processing -- popular understanding of corrosion and expansion

【云原生训练营】模块七 Kubernetes 控制平面组件:调度器与控制器

String functions that you need to know
随机推荐
在MapReduce中利用MultipleOutputs输出多个文件
高并发下之redis锁优化实战
C语言刷题~Leetcode与牛客网简单题
qt使用QZxing生成二维码
Tensorflow realizes verification code recognition (II)
redis单线程问题强制梳理门外汉扫盲
【pytorch学习笔记】Datasets and Dataloaders
【Transformer】入门篇-哈佛Harvard NLP的原作者在2018年初以逐行实现的形式呈现了论文The Annotated Transformer
Using notepad++ to build an arbitrary language development environment
Didi off the shelf! Data security is national security
Popular understanding of decision tree ID3
视觉上位系统设计开发(halcon-winform)-4.通信管理
Popular understanding of linear regression (I)
Redis lock Optimization Practice issued by gaobingfa
QT common sentence notes
The markdown file obtains the pictures of the network and stores them locally and modifies the URL
What is embedding (encoding an object into a low dimensional dense vector), NN in pytorch Principle and application of embedding
[combinatorial mathematics] binomial theorem and combinatorial identity (binomial theorem | three combinatorial identities | recursive formula 1 | recursive formula 2 | recursive formula 3 Pascal / Ya
【可能是全中文网最全】pushgateway入门笔记
Detailed pointer advanced 2
