当前位置:网站首页>[C language] string function
[C language] string function
2022-07-07 18:24: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
We learned from 4 A function ——strlen\strcpy\strcat\strcmp, The length of these functions is unlimited , today , We naturally want to introduce some other functions . The content may be relatively large .
List of articles
String function with limited length
strncpy
char * strncpy ( char * destination, const char * source, size_t num );
- Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
- Copy num Characters from the source string to the target space .
- If the length of the source string is less than num, After copying the source string , Add... After the target 0, until num individual .
below , Let's test it briefly :
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[20] = "abcdef";
char arr2[] = "hello world";
strncpy(arr1, arr2, 5);
printf("%s\n", arr1);
return 0;
}
function :
Let's take a look at the The first 3 spot :
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[20] = "abcdef";
char arr2[] = "ghi";
strncpy(arr1, arr2, 5);//arr2 Only 3 Here you have to copy 5 individual , What's the matter
printf("%s\n", arr1);
return 0;
}
F10 Debug and check before copying arr1 and arr2 It looks like this :
After copying ?
We can see clearly that , It will be used when the content is not enough ’\0’ To add !
strncat
char * strncat ( char * destination, const char * source, size_t num );
- Appends the first num characters of source to destination, plus a terminating null-character.
- If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[20] = "hello\0xxxxx";
printf("%s\n", arr1);
char arr2[] = "world";
strncat(arr1, arr2, 3);
printf("%s\n", arr1);
return 0;
}
As a result, we all know , What is the process like ? We might as well debug and have a look : Before appending :
After addition :
We can see clearly that , It will automatically add a ’\0’
What if the additional length is larger than itself ? Will it be like strncpy You can make up as many as you like ’\0’ Well ? Test a piece of code :
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[20] = "hello\0xxxxx";
printf("%s\n", arr1);
char arr2[] = "abc";
strncat(arr1, arr2, 6);
printf("%s\n", arr1);
return 0;
}
Before addition :
After addition :
The answer is No , Only one will be added ’\0’. By simple analysis , We probably know strncat Principle .
strncmp
int strncmp ( const char * str1, const char * str2, size_t num );Compare to a different character or the end of a string or num Compare all the characters .
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[] = "abcdef";
char arr2[] = "abc";
int ret = strncmp(arr1, arr2, 4);
printf("%d\n", ret);
if (ret == 0)
{
printf("==\n");
}
else if (ret < 0)
{
printf("<\n");
}
else
{
printf(">\n");
}
return 0;
}

actually , There are more functions n There will be more length restrictions , It doesn't make much difference , The string function with limited length makes the code more rigorous , We try to use .
String search
strstr
char * strstr ( const char *str1, const char * str2);Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
Simple understanding , This function is the function to find the substring
#include <stdio.h>
#include <string.h>
int main()
{
char email[] = "[email protected]";
char substr[] = "eichang";
char*ret = strstr(email, substr);
if (ret == NULL)
{
printf(" Substring does not exist \n");
}
else
{
printf("%s\n", ret);
}
return 0;
}

How to use it is not the point , The key point is how to simulate the implementation !
strstr Simulation Implementation of
Let's talk about the search process first :
Can be divided into Two kinds of To illustrate the situation :
A kind of It's a simple case : One match will find
Another kind It's a complicated situation : The first match was not found , You need to record the current location , Keep matching , It takes many times to find

The following is a simple simulation :
#include <assert.h>
#include <stdio.h>
char*my_strstr(const char*str1,const char*str2)
{
assert(str1 && str2);
const char* s1 = str1;
const char* s2 = str2;
const char* p = str1;
while (*p)
{
s1 = p;
s2 = str2;
while (*s1!='\0'&&*s2!='\0'&&* s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)p;
}
p++;
}
return NULL;
}
int main()
{
char email[] = "[email protected]";
char substr[] = "eichang";
//char*ret = strstr(email, substr);
char* ret = my_strstr(email, substr);
if (ret == NULL)
{
printf(" Substring does not exist \n");
}
else
{
printf("%s\n", ret);
}
return 0;
}
You can use the substring here KMP Algorithm , But it's more complicated , We won't expand the description .
strtok
char * strtok ( char * str, const char * sep );sep The parameter is a string , Defines the set of characters used as separators
The first parameter specifies a string , It contains 0 One or more by sep A character separated by one or more separators in a string remember .
strtok Function found str The next mark in , And use it \0 ending , Returns a pointer to the tag .( notes : strtok Function changes the string being manipulated , So it's using strtok The string segmented by function is usually the content of temporary copy And it can be modified .)
strtok The first argument of the function is not NULL , Function will find str The first mark in ,strtok The function will save it in the string Position in .
strtok The first argument to the function is NULL , The function will start at the same position in the string that is saved , Find the next target remember .
If there are no more tags in the string , Then return to NULL The pointer .
I think this is a strange function , However, it does not prevent us from recognizing that it cuts strings
#include <stdio.h>
#include <string.h>
int main()
{
const char* sep = "@.";
char email[] = "[email protected]";
char cp[30] = {
0 };
strcpy(cp, email);
char*ret = strtok(cp, sep);
printf("%s\n", ret);
ret = strtok(NULL, sep);
printf("%s\n", ret);
ret = strtok(NULL, sep);
printf("%s\n", ret);
return 0;
}

How and for Loop linked
#include <stdio.h>
#include <string.h>
int main()
{
const char* sep = "@.";
char email[] = "[email protected]";
char cp[30] = {
0 };
strcpy(cp, email);
char* ret = NULL;
for (ret = strtok(cp, sep); ret != NULL; ret = strtok(NULL, sep))
{
printf("%s\n", ret);
}
return 0;
}
Error message report
strerror
char * strerror ( int errnum );Return error code , The corresponding error message .
#include <stdio.h>
#include <string.h>
int main()
{
printf("%s\n", strerror(0));
printf("%s\n", strerror(1));
printf("%s\n", strerror(2));
printf("%s\n", strerror(3));
printf("%s\n", strerror(4));
printf("%s\n", strerror(5));
}

These do not need us to remember ,error-C A global error code storage variable of language settings
for instance :
#include <stdio.h>
#include <string.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
else
{
}
return 0;
}

Character classification function
There are many functions , Scattered , Does not Give examples one by one to illustrate , ad locum , You can know and practice by yourself :
function If his parameters meet the following conditions, it returns true
iscntrl Any control character
isspace Blank character : Space ‘ ’, Change the page ‘\f’, Line break ’\n’, enter ‘\r’, tabs ’\t’ Or vertical tabs ’\v’
isdigit Decimal number 0~9 isxdigit Hexadecimal number , Include all decimal digits , Lowercase letters af, Capital AF
islower Lowercase letters a~z
isupper Capital A~Z
isalpha Letter az or AZ
isalnum Letters or numbers ,az,AZ,0~9
ispunct Punctuation , Any graphic character that is not a number or letter ( Printable )
isgraph Any graphic character
isprint Any typeable character , Including graphic characters and white space characters
#include <stdio.h>
#include <ctype.h>
int main()
{
int i = 0;
char str[] = "Test String.\n";
char c;
while (str[i])
{
c = str[i];
if (isupper(c))
c = tolower(c);
putchar(c);
i++;
}
return 0;
}


边栏推荐
- SD_DATA_RECEIVE_SHIFT_REGISTER
- Tips of this week 135: test the contract instead of implementation
- Discuss | what preparations should be made before ar application is launched?
- < code random recording two brushes> linked list
- Introduction to OTA technology of Internet of things
- 现在网上期货开户安全吗?国内有多少家正规的期货公司?
- 2021年全国平均工资出炉,你达标了吗?
- 用存储过程、定时器、触发器来解决数据分析问题
- pip相关命令
- Year SQL audit platform
猜你喜欢

【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题

手撕Nacos源码(先撕客户端源码)

More than 10000 units were offline within ten days of listing, and the strength of Auchan Z6 products was highly praised

Understanding of 12 methods of enterprise management

AI 击败了人类,设计了更好的经济机制

Deep learning - make your own dataset

Introduction to OTA technology of Internet of things

Mui side navigation anchor positioning JS special effect
![[principles and technologies of network attack and Defense] Chapter 5: denial of service attack](/img/18/ac8b4c0dba4dd972df119d2f670416.png)
[principles and technologies of network attack and Defense] Chapter 5: denial of service attack

卖空、加印、保库存,东方甄选居然一个月在抖音卖了266万单书
随机推荐
物联网OTA技术介绍
Mui side navigation anchor positioning JS special effect
备份阿里云实例-oss-browser
Wireshark分析抓包数据*.cap
idea彻底卸载安装及配置笔记
PHP面试题 foreach($arr as &$value)与foreach($arr as $value)的用法
[paddleseg source code reading] add boundary IOU calculation in paddleseg validation (1) -- val.py file details tips
科学家首次观察到“电子漩涡” 有助于设计出更高效的电子产品
Discuss | frankly, why is it difficult to implement industrial AR applications?
云安全日报220707:思科Expressway系列和网真视频通信服务器发现远程攻击漏洞,需要尽快升级
[4500 word summary] a complete set of skills that a software testing engineer needs to master
Discuss | what preparations should be made before ar application is launched?
Tips for this week 140: constants: safety idioms
线程池和单例模式以及文件操作
Sanxian Guidong JS game source code
[answer] if the app is in the foreground, the activity will not be recycled?
2022年理财有哪些产品?哪些适合新手?
[论文分享] Where’s Crypto?
[trusted computing] Lesson 11: TPM password resource management (III) NV index and PCR
Taffydb open source JS database





