当前位置:网站首页>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 !

边栏推荐
- Jvm-02-class loading subsystem
- Relationship between truncated random distribution and original distribution
- 使用JMeter对WebService进行压力测试
- [daily training] 395 Longest substring with at least k repeated characters
- [combinatorics] permutation and combination (set permutation, step-by-step processing example)
- Win10 enterprise 2016 long term service activation tutorial
- 【日常训练】395. 至少有 K 个重复字符的最长子串
- Idea does not specify an output path for the module
- [combinatorics] combinatorial identities (recursive combinatorial identities | sum of variable terms | simple combinatorial identities and | sum of variable terms | staggered sums of combinatorial ide
- Jvm-06-execution engine
猜你喜欢

【pytorch学习笔记】Datasets and Dataloaders

需要知道的字符串函数

The state does not change after the assignment of El switch

百度智能云助力石嘴山市升级“互联网+养老服务”智慧康养新模式

Jvm-04-runtime data area heap, method area

第04章_逻辑架构

【云原生训练营】模块八 Kubernetes 生命周期管理和服务发现

String functions that you need to know

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

Final review points of human-computer interaction
随机推荐
详解指针进阶2
[combinatorics] combinatorial identities (recursive combinatorial identities | sum of variable terms | simple combinatorial identities and | sum of variable terms | staggered sums of combinatorial ide
Halcon与Winform学习第一节
Solve the problem that pushgateway data will be overwritten by multiple push
[daily training] 395 Longest substring with at least k repeated characters
视觉上位系统设计开发(halcon-winform)-2.全局变量设计
Using notepad++ to build an arbitrary language development environment
SQL server安装位置改不了
Jvm-05-object, direct memory, string constant pool
【pytorch学习笔记】Transforms
What are the composite types of Blackhorse Clickhouse, an OLAP database recognized in the industry
官网MapReduce实例代码详细批注
Redis single thread problem forced sorting layman literacy
redis缓存穿透,缓存击穿,缓存雪崩解决方案
mysql innodb 存储引擎的特性—行锁剖析
win32创建窗口及按钮(轻量级)
视觉上位系统设计开发(halcon-winform)-5.相机
Tensorflow realizes verification code recognition (I)
Qt常用语句备忘
Concurrency-01-create thread, sleep, yield, wait, join, interrupt, thread state, synchronized, park, reentrantlock
