当前位置:网站首页>Detailed explanation of character function and string function (including simulation implementation)
Detailed explanation of character function and string function (including simulation implementation)
2022-06-11 07:44:00 【Fried tomatoes 110】
Catalog
1. Find string length function
2. Unlimited length string function
3. String function with limited length
5. Memory manipulation function
1. Find string length function
1.1 strlen
size_t strlen ( const char * str );
Used to find the length of a string .
String to '\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 .
The return value of the function is size_t, Is the number of strings , It's an unsigned integer .
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str[] = "duachebdbvla";
int sz = sizeof(str);
printf("%d", sz);
return 0;
}strlen Simulation Implementation of :
int my_strlen(const char* str)
{
assert(str);
int i = 0;
while (*str++)
{
i++;
}
return i;
}
2. Unlimited length string function
2.1 strcpy
char* strcpy(char * destination, const char * source );
Used to copy strings .
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 .
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "duachebdbv";
char str2[20] = "0";
strcpy(str2, str1);
printf(str2);
return 0;
}strcpy Simulation Implementation of :
char* my_strcpy(char*des,const char*src)
{
char* tmp = des;
assert(des && src);
while (*des++ = *src++;)
{
;
}
return tmp;
}2.2 strcmp
int strcmp ( const char * str1, const char * str2 );
Used to compare the size of strings .
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

Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "asdfghj";
char str2[20] = "awsdefghjjjk";
int ret=strcmp(str1, str2);
if (ret > 0)
{
printf("str1>str2");
}
else if (ret == 0)
{
printf("str1=str2");
}
else
{
printf("str1<str2");
}
return 0;
}notes : because strcmp Not comparing string lengths , Instead, compare the characters corresponding to the same subscript ascii Code value , If the characters are the same , Then compare the next , Until they are different . This code is due to str1[0] and str2[0] All are a, So compare the next character ,str1[1] yes ‘s’,str2[1] yes ‘w’, and s Of ascii The code value is less than w Of ascii value , So it returns a value less than 0 The integer of .
Simulation Implementation :
int my_strcmp(const char* str1, const char* str2)
{
assert(*str1 && *str2);
while (*str1 || *str2)
{
if (*str1 == *str2)
{
str1++;
str2++;
}
else
{
return *str1 - *str2;
}
}
return 0;
}
2.3 strcat
char * strcat ( char * destination, const char * source );
Copy one string to the end of another .
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 .
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "kajhcjeef";
char str2[40] = "jdsafbkw";
strcat(str2, str1);
printf(str2);
return 0;
}
Simulation Implementation :
char* my_strcat(char* des, const char* scr)
{
char* tmp = des;
assert(des && scr);
while (*des)
{
des++;
}
while (*des++=*scr++)
{
;
}
return tmp;
}The above strcoy,strcmp,strcat The implementation of these three functions is nothing more than to encounter ‘\0’ Stop or compare the size of two characters , It has nothing to do with the length of the string , Therefore, we can think that the length of these three functions is unlimited . And the next strncoy,strncmp,strncat It's about length .
3. String function with limited length
3.1 strncoy
char * strncpy ( char * destination, const char * source, size_t num );
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 .
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "kajhcjeef";
char str2[40] = "jdsafbkw";
strncpy(str2, str1,3);
printf(str2);
return 0;
}
Simulation Implementation :
char* my_strncpy(char* des, const char* scr, int num)
{
char* ret = des;
assert(des && scr);
while (num--&&*scr&&*des)
{
*des++ = *scr++;
}
return ret;
}3.2 strncmp
int strncmp ( const char * str1, const char * str2, size_t num );
Used to compare two strings num The size of characters .
Compare to two different characters stop or a string end stop or the number of comparison characters is num Stop after . When str1 Before num A string of characters is greater than str2 Before num A string consisting of characters returns a value greater than 0 The integer of , When equal, return 0, Returns a less than when less than 0 The integer of .
Use samples :
#include<string.h>
#include<stdio.h>
int main()
{
char str1[20] = "jajhcjeef";
char str2[40] = "jasafbkwn";
int ret=strncmp(str1, str2, 3);
printf("%d", ret);
return 0;
}
Simulation Implementation :
int my_strncmp(const char* str1, const char* str2, int num)
{
assert(str1 && str2);
while (num--&&(*str1||*str2))
{
if (*str1 != *str2)
{
return *str1- *str2;
}
else
{
str1++;
str2++;
}
}
return 0;
}
3.3 strncat
char * strncat ( char * destination, const char * source, size_t num );
Used to append strings .
The string source Before num Characters copied to string destination At the end of ( from ‘\0’ Start ).
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "jajhcjeef";
char str2[40] = "ja";
strncat(str2, str1, 6);
printf(str2);
return 0;
}
Simulation Implementation :
#include<stdio.h>
#include<assert.h>
char* my_strncat(char* des, const char* scr, int num)
{
char* ret = des;
assert(des && scr);
while (*des)
{
des++;
}
while (num && ((*des++ = *scr++) != '\0'))
{
num--;
}
if (num == 0)
*des = '\0';
return ret;
}4. String search
4.1 strstr
char * strstr ( const char *str1, const char * str2);
In string str1 Find string in str2, If you find , Then return the string str1 And string str2 The starting address of the same fragment string .
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "jajhcjeef";
char str2[40] = "cj";
char* tmp = strstr(str1, str2);
printf("%s",tmp);
return 0;
}
Simulation Implementation :
#include<stdio.h>
//#include<string.h>
#include<assert.h>
char* my_strstr(const char* str, const char* substr)
{
const char* s1 = str;
const char* s2 = substr;
const char* cur = str;
assert(str && substr);
if (*substr == '\0')
{
return (char*)str;
}
while (*cur)
{
s1 = cur;
s2 = substr;
while (*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
return (char*)cur;
cur++;
}
return NULL;
}4.2 strtok
char * strtok ( char * str, const char * sep );
Used to split the string according to the separator specified by the user .
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 . The second parameter sep It's a string , Defined A collection of characters used as separators .
strtok Function found str The next mark in , And use it \0 ending , Return to one Pointer to this marker .( 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 .
Use samples :
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50] = "zhouling#[email protected]";
const char sep[10] = "#[email protected]";
char arr[50];
char* ch = NULL;
strcpy(arr, str1);
for (ch = strtok(arr, sep);ch != NULL; ch = strtok(NULL, sep))
{
printf("%s\n", ch);
}
return 0;
}
5. Memory manipulation function
5.1 memcpy
void*memcpy(void*dest,constvoid*src,size_tcount);
function memcpy from source The position of begins to be copied back num Bytes of data to destination Memory location for .
This function is encountering '\0' It doesn't stop . This function is related to strcmp A bit similar , But this function can copy Integer or other type The data of .
If source and destination There is any overlap , The results of replication are undefined .
Use samples 1:
#include<stdio.h>
int main()
{
char str1[] = "zhouling";
char str2[] = "mlanvkml";
int arr1[4] = { 1,2,3,4 };
int arr2[4] = { 5,6,7,8 };
int i = 0;
char*str = memcpy(str2, str1, sizeof(str1[0]) * 2 );
int* arr = memcpy(arr1, arr2, sizeof(arr1[0]) * 2);
for (i = 0; i < 4; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
printf("%s", str);
return 0;
}
Use samples 2:
#include<stdio.h>
#include<string.h>
struct PeoPle
{
char name[20];
int age;
}People1,People2;
int main()
{
char myname[] = "zhouling";
People1.age = 18;
memcpy(People1.name, myname, sizeof(myname)+1);
memcpy(&People2, &People1, sizeof(People1));
printf("People2:%s %d", People2.name, People2.age);
return 0;
}
Simulation Implementation :
void* my_memcpy(void* dst, const void* src, size_t count)
{
void* ret = dst;
assert(dst&&src);
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
return ret;
}5.2 memmove
void * memmove ( void * destination, const void * source, size_t num );
Function and memcpy Is essentially the same , But and memcpy The difference is that memmove The source and target memory blocks processed by the function can overlap .
If the source space and the target space overlap , It's best to use memmove Function processing .
Use samples :
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "I don't love you and you like.......me";
memmove(str + 25, str + 2,11);
puts(str);
return 0;
}
Simulation Implementation :
void * my_memmove(void* des, const void* scr, int num)
{
void* ret = des;
assert(des && scr);
while (num--)
{
if (des < scr)
{
*((char*)des)++ = *((char*)scr)++;
}
else
{
*((char*)(des)+num) = *((char*)(scr)+num);
}
}
return ret;
}5.3 memcpy
intmemcmp(constvoid*buf1,constvoid*buf2,size_tcount);
Compare from ptr1 and ptr2 The pointer starts with num Bytes , The former is greater than the latter and returns a greater than 0 The integer of , Otherwise, it returns a value less than 0 The integer of , Equal to return to 0.

Use samples :
#include <stdio.h>
#include <string.h>
int main()
{
char buffer1[] = "zhouzhou";
char buffer2[] = "zhdhZhou";
int n;
n = memcmp(buffer1, buffer2, 2);
if (n > 0) printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
else if (n < 0) printf("'%s' is less than '%s'.\n", buffer1, buffer2);
else printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
return 0;
}

Simulation Implementation :
int my_memcmp(const void* buf1, const void* buf2, size_t count)
{
void* tmp1 = buf1;
void* tmp2 = buf2;
assert(buf1 && buf2);
while (count--)
{
if (*((char*)tmp1) != *((char*)tmp2))
{
return *((char*)tmp1) - *((char*)tmp2);
}
((char*)tmp1)++;
((char*)tmp2)++;
}
} Okay , This is the end of today's learning notes sharing , Let's give a compliment to the friends here 
边栏推荐
- C language to achieve minesweeping games
- Analyse du contrat du modèle de taux composé
- 134. 加油站
- 黑群晖DSM7.0.1物理机安装教程
- Ffmpeg extraction package format extracts AAC and customizes adtc header to realize arbitrary frame decoding
- 欧拉定理及扩展(附证明)
- Classes and objects (Part 2)
- 20200803 T3 my friends [divide and conquer NTT optimization recursion]
- 运筹学导论
- Djikstra solves the shortest circuit with negative weight
猜你喜欢

Simple configuration of vscade

C language - Growth Diary -02- function

【AtCoder2306】Rearranging(拓扑)

Deux diplômés, la Banque a externalisé le travail d'essai pendant plus de quatre mois. Parler de vrais sentiments...

Paging of the flask page

C language to write a calculator calculation logic

The solution of "no startup device" after running Bochs

Qunhui ds918 creates m.2 SSD read / write cache

mpi

Zero foundation self-study SQL course | outer join external connection
随机推荐
[IOT] project management: how to build a better cross functional team?
wordcloud的使用
【HDU6357】Hills And Valleys(DP)
如何准备PMP新版大纲考试?
远程办公经验分享 | 社区征文
Uoj 554 [unr 4] challenges Hamilton [find Hamilton path (adjustment method)]
【NOIP2016 D1T3】换教室(期望DP+Floyd)(究极思维陷阱!)
multi-sig SC
排序——归并排序
Use of wordcloud
Lesson 1 about Xiaobai's C language
multi-sig SC
What is the difference between gaussdb for redis and redis?
TiDB Cloud 上线 Google Cloud Marketplace,以全新一栈式实时 HTAP 数据库赋能全球开发者
[poj3691] DNA repair (AC automata +dp)
C language to write a calculator MVC (very interesting code architecture callback and constructor mode and the use of pointer functions)
【AtCoder1998】Stamp Rally(整体二分+并查集)
2021-10-24
【IoT】智能硬件:如何获取硬件产品的wifi信号强度
[atcoder2305] declining (game)