当前位置:网站首页>(advanced usage) C language string function
(advanced usage) C language string function
2022-04-22 02:37:00 【Descosmos】
Before the order
When you learn C Operation of language string , We know how strings are defined , String output mode , It includes input and output statements of strings , for example puts,gets ,fputs etc. .
There are also string operation functions , for example strcpy,strcmp,strcat, etc. . After finally understanding the robustness of the function , To study the strncpy And other functions that can improve the robustness of the code .
Introduce
In the use of string output statements , Always can't do without NUL, This terminator .
NUL , stay C There are basically in every string of language , It exists in the string , But not part of the string . When printing related strings , such as printf Use in %s To print strings . printf Execution time , meet NUL The character stops executing .
Existing problems
- Strlen Return value problem of
Generally, when measuring the length of a string , We will use string.h In the library strlen
Function to measure . But when you see strlen When defining the function of , You will find a little different .
strlen Function prototype of
size_t strlen( char const *string );
among size_t Is an unsigned integer type , It's defined in stddef.h in .
typedef unsigned int size_t
therefore , strlen The return value of is always greater than or equal to 0 The integer number of . If you still don't understand the importance of this , Let's look at a piece of code .
char str[] = "For text";
if( strlen(str)-10 >= 0 ){
printf("Alright.\n");
}
else{
printf("Error.\n");
}
Judge the result of this code ,str The length of is undoubtedly 8, Then the execution output will be “Error” Well ?

Unfortunately , No . because strlen The return value type of is unsigned int Therefore, the return value can never be greater than 0. If you want to eliminate this problem , Force the type of the return value to int The type is enough .
- strcpy Replication problem of
The function used to copy a string is usually strcpy , The function prototype is as follows :
char *( char *des ,char const *src );
The string src Assign parameters to des , When in src Meet in NUL when , Stop assignment .
char str[] = "frank francis";
char text[] = {'t','j','\0','o','h','s','o','n'};
strcpy(str,text);
printf("%s\n",str);
What will be the result of implementation ?

because text[2] The value of is '\0’ , Therefore, when the signal is encountered during execution, it exits the function .
So for strncpy Will this function encounter the same problem ? The answer is yes . Put... In the code above strcpy Change it to strncpy after , The resulting structure is still “tj”.
Extended to other string operation functions , and strcpy equally , for example strcat ,strcmp ,strstr You will still meet ‘\0’ Then end the execution .
So for the middle existence ’\0’ String to operate on , How to do it? ?
String memory operation
When you meet... In a string NUL Character time , Be able to NUL The following characters are processed , This is the time C A set of functions are defined in the language standard library , Make it possible to NUL Operate on the character after the character .

among memcpy It's the copy function ,memmove The function and memcpy almost , But when the copied source and target parameters may overlap , You should use memmove .
memcmp For the comparison function , Function and strcpy be similar .
memchr Find function for character , Co search length Characters .
memset Set the function for the character , take length All previous characters use ch To replace .
So let's go back to the second part of the code :
char str[] = "frank francis";
char text[] = {'t','j','\0','o','h','s','o','n'};
//strcpy(str,text);
memcpy(str,text,strlen(text));
printf("%s\n",str);

In this way, the use of strcpy The case when . The reason is , Because memcpy It's an operation on memory . stay C++ reference About memcpy In the introduction :

And for strcpy It is :

Of course , Encountered in string NUL It's rare to see the situation of , Therefore use strcpy It can basically meet the daily needs .
summary
strcpy Is defined as , String assignment function , And in the “mem” Functions in the series , The types of arguments and functions are void , So you can use “mem” A series of functions to operate on different types of variables or structures .
版权声明
本文为[Descosmos]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220230319453.html
边栏推荐
- Pv-tsm principle and MATLAB simulation
- 用zlib压缩、解压缩流、判断是否压缩过了
- Developer openshift4 Getting Started tutorial - 16 - use init container to mount pinpoint APM monitoring
- 创建双向链表(详解)
- AI应用说-智慧农场(牛场无人监控)
- Unity Game Optimization - Third Edition 阅读笔记 Chapter 1 分析性能问题
- Software testing · bad taste
- (进阶用法) C语言字符串函数
- Ren Jie, chief scientist of rongyun: the Internet is unstoppable, but there are always young people
- 安装部署phpStudy+DVWA漏洞演练平台
猜你喜欢

详解各类云计算模型,企业如何使用每种模型提高业务生产力?
![[timing] dcrnn: a spatiotemporal prediction network for traffic flow prediction combining diffusion convolution and GNN](/img/65/6bb2892f4aabe47002ada72ed139db.png)
[timing] dcrnn: a spatiotemporal prediction network for traffic flow prediction combining diffusion convolution and GNN

How to provide CPU branch prediction efficiency at the code level

STM32 flash operation

Pv-tsm principle and MATLAB simulation

吴恩达机器学习作业——逻辑回归

2022年软件设计师考试知识点:线性表

Embedded AI

身份认证和访问控制

Development management · Huawei IPD
随机推荐
Wu Enda's machine learning assignment -- Logical Regression
Fluent music player audioplayer
STM32 FLASH操作
创建双向链表(详解)
Why can the Internet industry attract more and more young people? Especially programmers
Unity game optimization - third edition reading notes Chapter 1 analyze performance problems
我要开始学canvas了
Formation pratique à la sécurité de l'information financière - 22 / 4 / 19 (Partie I)
Alibaba P9 explains high concurrency in detail, and shows you how Taobao can resist large-scale second kill activities such as double 11
遇到个奇怪的问题,同时开启本地和远程两个事务,远程事务是sql2000没问题,是sql2008的不报错,但是写不上数据
Uniapp handles forced refresh
【时序】DCRNN:结合扩散卷积和GNN的用于交通流量预测的时空预测网络
数据库案例这一节内容
Ren Jie, chief scientist of rongyun: the Internet is unstoppable, but there are always young people
A general tool class for adding, deleting, querying and modifying databases based on Hikari connection pool
【※ LeetCode 剑指 Offer 12. 矩阵中的路径(简单)】
Oracle表关联发散
Interview question: use the program to realize the alternating printing of odd and even numbers from 0 to 100 by two threads
The accuracy of Microsoft's new tools is 80%? Programmer: Thank you
2022年软件设计师考试知识点:线性表