当前位置:网站首页>[C language] string function and Simulation Implementation strlen & strcpy & strcat & StrCmp
[C language] string function and Simulation Implementation strlen & strcpy & strcat & StrCmp
2022-07-05 19:42:00 【Ordinary person 1】
author :@ Ordinary person 1
special column :《C Language from 0 To 1》
In a word : In the past , All is prologue
explain : The past is irreparable , The future can change
List of articles
Preface
We know , stay C The processing of characters and strings in languages is very frequent , however C The language itself has no string type ( Unlike other languages, direct String Can solve ), stay C Strings in languages are usually placed in constant strings or character arrays .
String constants apply to string functions that do not modify it .
We mainly introduce some string functions this time .
- About learning some strange functions : We can go through cplusplus.com Learn to understand , Know the meaning represented by the parameters and the functions realized are the above , This can make us get twice the result with half the effort ! If you don't understand English , We can translate it into Chinese that we are familiar with .
- Be sure to implement the code yourself , Don't eat fat in one breath
* Find the string length ——strlen()
About **strlen()** We need to know a few points :
size_t strlen ( const char * str );// Returns an unsigned integer
- The string has ‘\0’ As an end sign ,strlen Function returns in a string ‘\0’ The number of characters that appear before ( No package contain ‘\0’ ).
- The string that the argument points to must be in ‘\0’ end .
- Note that the return value of the function is size_t, It's unsigned ( Fallible )
- Learn to strlen Simulation Implementation of function
For the first 3 How can we understand it? We can take an example :
#include <stdio.h>
#include <string.h>
int main()
{
// Returns an unsigned integer
if (strlen("abc") - strlen("abcdef") > 0)
{
printf(">\n");
}
else
{
printf("<\n");
}
return 0;
}
What is the output result
yes :>
because strlen() Returns an unsigned integer , although 3-6<0, But for unsigned numbers , How can there be negative numbers ? So the result must be > Number
We can test and run the results :
The main content of this blog is the simulation and implementation of functions
So let's talk about strlen() Three simulation implementation methods of :
1. Counter method
Directly define a variable to count the length of the string :
#include <stdio.h>
#include <string.h>
#include <assert.h>
// Counter method
size_t my_strlen(const char*str)
{
int count = 0;
assert(str);
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);
printf("%u\n", n);
return 0;
}
meanwhile , We need to be more rigorous , Pay attention to some details :
- The first one is const modification , We just need to visit , No modification is required
- The second one is assert Assertion , What if it's empty ? This is it. assert It's no longer useful
- The third is the return value size_t Unsigned
2. The pointer - Pointer method
#include <stdio.h>
#include <string.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
assert(str);
char* ret = str;
while (*str != '\0')
{
str++;
}
return str - ret;
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);
printf("%u\n", n);
return 0;
}
Pointer minus pointer is the number of elements , So we record the initial address , The length can be obtained by subtracting the pointer address just recorded from the last pointer address !
3. recursive
Finding out the recursive conditions can perfectly simulate the implementation strlen(). The following code implementation :
#include <stdio.h>
#include <string.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
return 1 + my_strlen(str + 1);
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);
printf("%u\n", n);
return 0;
}
test run :
* Unlimited length string function
strcpy
about strcpy(), We need to know a few points :
char* strcpy(char * destination, const char * source );
- Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). A simple understanding is a copy of a string , However, the following points should be paid attention to in copying :
- 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 . Learn to simulate .
I think the most important thing about this function is : The first parameter is the destination string , The second parameter is the string from the source . The second parameter is unchangeable , It can be used const To modify . This is more important .
Now let's simulate it :
// Simulation Implementation
#include <stdio.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest);
assert(src);
char* ret = dest;
while (*src)
{
*dest++ = *src++;
}
*dest = *src;
return ret;
}
int main()
{
char arr1[] = "abcdef";
char arr2[20] = {
0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
For this simulation implementation, we can optimize , Make it look simpler
#include <stdio.h>
char* my_strcpy(char* dest, char* src)
{
assert(dest && src);
char* ret = dest;
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[] = "abcdef";
char arr2[20] = {
0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
Test run results :
strcat
char * strcat ( char * destination, const char * source );
- Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination. Simple understanding , It is the addition of string .
- 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 . The string appends itself , how ?
With the above knowledge points , about strcat We have a good understanding , Next, let's simulate the implementation :
#include <stdio.h>
// String append
// String append
char* my_strcat(char* dest, const char* src)
{
assert(dest && src);
int ret = dest;
while (*dest != '\0')
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = "hello ";
strcat(arr1, "world");
//my_strcat(arr1, "world");
// Add to yourself ?
//my_strcat(arr1, arr1);// This is wrong , Destroy yourself .\0 Be missing
printf("%s\n", arr1);
return 0;
}
test run :
Someone here will ask : Add it to yourself ? think about it , This is the wrong way , Because you will find , The process of adding yourself has changed itself ,'\0’ It is covered. , It's impossible to achieve . Whether it is our own simulation or library function , I can't add myself .
strcmp
int strcmp ( const char * str1, const char * str2 );
- This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. Simply speaking , Is to compare strings .
- The standard stipulates : The first string is larger than the second string , Return greater than 0 The number of
- The first string is equal to the second string , Then return to 0
- The first string is less than the second string , Then return less than 0 The number of
- So how to judge two strings ? The comparison is the corresponding ASCII Code value
First, let's briefly understand the library function :
#include <stdio.h>
int main()
{
int ret = strcmp("abbb", "abq");
printf("%d", ret);
return 0;
}
Will get :
Because third b Less than q Of ASCII Code value , Natural return -1. This is it. strcmp The basic principle of .
But here we need to simulate it , How to simulate the implementation
#include <stdio.h>
int my_strcmp(const char* s1, const char* s2)
{
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return 0;
}
s1++;
s2++;
}
if (*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
char* p = "abcdef";
char* q = "abbb";
int ret = my_strcmp(p, q);
if (ret>0)
{
printf("p>q");
}
else if(ret <0)
{
printf("p<q");
}
else
{
printf("p=q");
}
return 0;
}
Test run results :
Is that over ? did not , We can optimize the code of simulation implementation and make it simpler :
// Optimize simulation implementation
#include <stdio.h>
#include <assert.h>
int my_strcmp(const char* s1, const char* s2)
{
assert(s1 && s2);
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return 0;
}
s1++;
s2++;
}
return *s1 - *s2;
}
int main()
{
char* p = "abcdef";
char* q = "abbb";
int ret = my_strcmp(p, q);
if (ret>0)
{
printf("p>q");
}
else if(ret <0)
{
printf("p<q");
}
else
{
printf("p=q");
}
return 0;
}
be aware :
No specific requirements <0 What's the number of , Or say >0 What's the number of , Let's just subtract .
Test and run the code :
* summary
This is the end of the introduction and Simulation of string length calculation and string function with unlimited length , Then consider the actual situation , If we learn too many library functions at one time, it is not conducive to the formation of memory , Not proficient in functions , This blog first introduces this 4 Implementation of a function , The rest will be left next time !
At the same time, remember to summarize more , Knock the code with more hands , Don't think you can understand it , The actual operation is different from your own idea , I hope you can practice more !
边栏推荐
- 【合集- 行业解决方案】如何搭建高性能的数据加速与数据编排平台
- 常用运算符与运算符优先级
- 使用 RepositoryProvider简化父子组件的传值
- Hiengine: comparable to the local cloud native memory database engine
- 司空见惯 - 英雄扫雷鼠
- 【obs】QString的UTF-8中文转换到blog打印 UTF-8 char*
- No matter how busy you are, you can't forget safety
- Which securities company is better and which platform is safer for mobile account opening
- 手机开户选择哪家券商公司比较好哪家平台更安全
- 【obs】libobs-winrt :CreateDispatcherQueueController
猜你喜欢
XaaS 陷阱:万物皆服务(可能)并不是IT真正需要的东西
Tutoriel de téléchargement et d'installation du progiciel fuzor 2020
IBM has laid off 40 + year-old employees in a large area. Mastering these ten search skills will improve your work efficiency ten times
Django uses mysqlclient service to connect and write to the database
Oracle fault handling: ora-10873:file * needs to be either taken out of backup or media recovered
Fuzor 2020 software installation package download and installation tutorial
Do you know several assertion methods commonly used by JMeter?
PHP利用ueditor实现上传图片添加水印
HiEngine:可媲美本地的云原生内存数据库引擎
Postman核心功能解析-参数化和测试报告
随机推荐
C application interface development foundation - form control (6) - menu bar, toolbar and status bar controls
Force buckle 729 My schedule I
Mariadb root用户及普通用户的密码 重置
国海证券在网上开户安全吗?
多分支结构
Concept and syntax of function
Android面试,android音视频开发
四万字长文说operator new & operator delete
通配符选择器
No matter how busy you are, you can't forget safety
That's awesome. It's enough to read this article
Django uses mysqlclient service to connect and write to the database
Float.floatToRawIntBits的返回值具体意思,将float转为byte数组
力扣 729. 我的日程安排表 I
Two pits exported using easyexcel template (map empty data columns are disordered and nested objects are not supported)
[OBS] qstring's UTF-8 Chinese conversion to blog printing UTF-8 char*
What is the function of okcc call center
Android interview, Android audio and video development
Shell编程基础(第8篇:分支语句-case in)
Add data to excel small and medium-sized cases through poi