当前位置:网站首页>C language: deep understanding of character functions and string functions (1)
C language: deep understanding of character functions and string functions (1)
2022-06-13 09:12:00 【Caixinzhi】
References in this article are from cplusplus Website :cplusplus.com - The C++ Resources Networkhttp://www.cplusplus.com/
Catalog
One 、strlen Find the string length
3、 ... and 、strcat Append string
5、 ... and 、strncpy Copy string
6、 ... and 、strncat Append string
7、 ... and 、strncmp Compare strings
One 、strlen Find the string length
First, I will briefly introduce the information I have found strlen:
Next , Use one strlen To introduce the simulation implementation strlen:
// Calculate string length
#include <stdio.h>
#include <string.h>
int main()
{
char arr[] = "abcdef";
int ret = strlen(arr);
printf("%d\n", ret);
return 0;
}
Simulation Implementation strlen The way to do this is 3 Kind of :
1. Calculator method
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strlen(const char* str)
{
assert(str);
int count = 0;
while (*str)
{
count++;
str++;
}
return count;
}
int main()
{
char str[] = "abcdef";
int ret = my_strlen(str);
printf("%d\n", ret);
return 0;
}
2. Cannot create timers for temporary variables ( Recursive method )
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strlen(const char* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
else
{
return 1 + my_strlen(str + 1);
}
}
int main()
{
char str[] = "abcdef";
int ret = my_strlen(str);
printf("%d\n", ret);
return 0;
}
3. The pointer - Pointer method ( Subtracting two pointers calculates the number of elements between two pointers )
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strlen(const char* str)
{
assert(str);
char* ptr = str;
while (*ptr != '\0')
{
ptr++;
}
return ptr - str;
}
int main()
{
char str[] = "abcdef";
int ret = my_strlen(str);
printf("%d\n", ret);
return 0;
}
Two 、strcpy Copy string
About strcpy Information :
Be careful :1. The source string must be in '\0' end
2. Will put... In the string '\0' Copy to target space
3. The target space has to be large enough , To ensure that the source string can be stored
4. The target space has to be variable
Next , Use one strcpy To introduce the simulation implementation strcpy:
//strcpy Copy string
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[] = "abcdef";
char arr2[] = "xxxxxxx";
char* ret = strcpy(arr2, arr1);
printf("%s\n", ret);
return 0;
}
Simulation Implementation strcpy:
#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strcpy(char* dest, const char* src)
{
char* ret = dest;
assert(dest && src);
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[] = "abcdef";
char arr2[20] = "xxxxxxxxx";
char* ret = my_strcpy(arr2, arr1);
printf("%s", ret);
return 0;
}
The specific simulation implementation method is introduced in detail in the previous article .
3、 ... and 、strcat Append string
About strcat Information :
Be careful :1. The source string must be in '\0' end
2. The target space has to be large enough , It can hold the contents of the source string
3. The target space must be modifiable
Next , Use one strcat To introduce the simulation implementation strcat:
//strcat Append string
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[10] = "abcd";
char arr2[] = "ef";
printf("%s\n", strcat(arr1, arr2));
return 0;
}
Simulation Implementation strcat:
#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strcat(char* dest, const char* src)
{
char* ret = dest;
assert(dest && src);
while (*dest)
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[10] = "abcd";
char arr2[] = "ef";
printf("%s", my_strcat(arr1, arr2));
return 0;
}
Simply speaking , Simulation Implementation strcat Is to find the target string '\0' The address of , Then add elements from this address .
Four 、strcmp Compare strings
of strcmp Information :
Next , Use one strcmp To introduce the simulation implementation strcmp:
//strcmp Compare strings
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[] = "abc";
char arr2[] = "abc";
int ret = strcmp(arr1, arr2);
if (ret < 0)
{
printf("arr1<arr2");
}
else if (ret > 0)
{
printf("arr1>arr2");
}
else
{
printf("arr1=arr2");
}
return 0;
}
Simulation Implementation strcmp:
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strcmp(const char* arr1, const char* arr2)
{
assert(arr1 && arr2);
while (*arr1 == *arr2)
{
if (*arr1 == '\0')
{
return 0;
}
arr1++;
arr2++;
}
return *arr1 - *arr2;
}
int main()
{
char arr1[] = "abc";
char arr2[] = "abc";
int ret = my_strcmp(arr1, arr2);
if (ret > 0)
{
printf("arr1>arr2");
}
else if (ret < 0)
{
printf("arr1<arr2");
}
else
{
printf("arr1=arr2");
}
return 0;
}
Simulation Implementation strcmp The idea is : Compare each character in the string one by one , If equal, compare the next character , Until the comparison '\0' Also equal , Then judge that the two strings are equal ; If unequal characters are found in them , The result of subtracting two characters will be returned , Because subtracting two characters is actually their ASCII Code value subtraction , The return value is just int type .
thus , The above strcpy、strcat、strcmp All three string functions are called string functions with unlimited length , That is, the length of the operation string cannot be specified 、 Scope, etc ; But the next step is to introduce three string functions with limited length ——strncpy、strncat、strncmp, When they operate, they can specify the length of the operation string . The basic situation of these three string functions is similar to the above three , Just one more parameter , This parameter is used to specify the scope , So the following three string functions are only simulated , No more emphatic explanations .
5、 ... and 、strncpy Copy string
Simulation Implementation strncpy:
#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strncpy(char* dest, const char* src, size_t num)
{
assert(dest && src);
char* ret = dest;
while (num--)
{
*dest = *src;
if (*dest == '\0')
{
return ret;
}
dest++;
src++;
}
return ret;
}
int main()
{
char arr1[10] = { 0 };
char arr2[] = "abcdef";
char* ret = strncpy(arr1, arr2, 4);
printf("%s\n", ret);
return 0;
}
6、 ... and 、strncat Append string
Simulation Implementation strncat:
#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strncat(char* dest, const char* src, size_t num)
{
char* ret = dest;
assert(dest && src);
while (*dest)
{
dest++;
}
while (num--)
{
*dest = *src;
if (*dest == '\0')
{
return ret;
}
dest++;
src++;
}
*dest = '\0';
return ret;
}
int main()
{
char arr1[10] = { 'a', 'b', 'c', 'd', '\0' };
char arr2[] = "efgh";
printf("%s\n", my_strncat(arr1, arr2, 2));
return 0;
}
7、 ... and 、strncmp Compare strings
Simulation Implementation strncmp:
#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strncmp(const char* arr1, const char* arr2, size_t num)
{
assert(arr1 && arr2);
while (num--)
{
if (*arr1 == *arr2)
{
if (*arr1 == '\0')
{
return 0;
}
arr1++;
arr2++;
}
else
{
return *arr1 - *arr2;
}
}
}
int main()
{
char arr1[] = "abcee";
char arr2[] = "abcef";
int ret = my_strncmp(arr1, arr2, 4);
if (ret > 0)
{
printf("arr1>arr2");
}
else if (ret < 0)
{
printf("arr1<arr2");
}
else
{
printf("arr1=arr2");
}
return 0;
}
What we should pay attention to here is , In addition to the original parameters, the three string functions with limited length , A parameter will also be added to specify the range , The type of this parameter is size_t type , So it can only be a positive integer , And in bytes .
边栏推荐
- Simulink variant model and variant subsystem usage
- Tutorial (5.0) 03 Security policy * fortiedr * Fortinet network security expert NSE 5
- 20220524 如何把CoppeliaSim安装到D盘
- Drill down to protobuf - Introduction
- Exporting MySQL data table documents using Navicat
- 20211006 积分、微分、投影均属于线性变换
- Spectre record
- redis 模糊查询 批量删除
- Use typescript to complete simple snake eating function
- Neo4j environment construction
猜你喜欢
[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp
C/S模型与P2P模型
Some websites of QT (software download, help documents, etc.)
final 原理
an error occurred while trying to rename a file in the destination directory code 5
Yolov5 face learning notes
How excel adds hyperlinks to some text in a cell
20211020 academician all drive system
Tutorial (5.0) 04 Fortint cloud services and scripts * fortiedr * Fortinet network security expert NSE 5
Simulink如何添加模块到Library Browser
随机推荐
torch. How to calculate addmm (m, mat1, mat2)
20211006 integral, differential and projection belong to linear transformation
What are the bank financial products? How long is the liquidation period?
简单实现数据库链接池
Sonar scan ignores the specified file
An error CV2 is reported when the picture is converted to grayscale cvtColor(img, cv2.COLOR_BGR2GRAY)
How many TCP connections can a machine create at most?
20211020 段院士全驱系统
【安全】零基礎如何從0到1逆襲成為安全工程師
Simulink variant model and variant subsystem usage
Tensorflow1.14 corresponds to numpy version
20211104 why are the traces of similar matrices the same
Summary of the first retrospective meeting
【网络安全】SQL注入新思维之webshell提权
教程篇(5.0) 02. 管理 * FortiEDR * Fortinet 网络安全专家 NSE 5
批量讀取文件夾下的全部語音文件
线上调试工具Arthas高级
Online debugging tool Arthas Foundation
Talking about acid of database
How Simulink adds modules to the library browser