当前位置:网站首页>[C language] string library function introduction and simulation
[C language] string library function introduction and simulation
2022-07-28 06:45:00 【HandsomeDog_ L】
Catalog
Introduction and Simulation of string library functions
Introduction and Simulation of string library functions
1.strlen
1.1 The functionality
Find the string length , Returns an unsigned number
1.2 The usage function
size_t strlen ( const char * str );
matters needing attention :
The string already has '\0' As an end sign ,strlen Function returns in a string '\0' The number of characters that appear before ( It doesn't contain '\0' ).
The string that the argument points to must be in '\0' end .
The return value of the function is size_t, It's unsigned ( Fallible )
1.3 Function simulation
// Counter
#include <stdio.h>
#include <string.h>
int my_strlen(const char* str)
{
int count = 0;
while (*str++ != '\0')
{
count++;
}
return count;
}
int main()
{
char* str1 = "abcdef";
int ret = my_strlen(str1);
printf("%d", ret);
return 0;
}
///
// Pointer subtraction // The two hands subtract , Indicates the element between the two ( The element type corresponds to the pointer type ) Number
int my_strlen(const char* start, int sz)
{
char* dest = &start[sz - 1];
int count = dest - start;
return count;
//char *p = s;
//while(*p != ‘\0’ )
//p++;
// return p-s;
}
/ Function recursion
int my_strlen(const char * str)
{
if(*str == '\0')
return 0;
else
return 1+my_strlen(str+1);
}
2.strcpy
2.1 The functionality
String copy , Copy the string from the source space to the target space , Returns a pointing to the target space char* The pointer
2.2 The usage function
char* strcpy(char * destination, const char *source);
matters needing attention :
The source string must be in '\0' end .
In the source string '\0' Copy to target space .
The target space must be large enough and variable , To ensure that the source string can be stored .
2.3 Function simulation
// simulation strcpy
#include<stdio.h>
#include<string.h>
#include<assert.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);// Assertion 、 Judge air safety 、 Good habit
char* tmp = dest;
while (*dest++ = *src++)
{
;
}
// After ++, Assign first , Post auto increment ;
return tmp;
}
int main()
{
char str1[20] = "abcdefg";
char str2[] = "hijkl";
//str1 More space than str2 The space is large .
char* ret = my_strcpy(str1, str2);
printf("%s", ret);
// Same as printf( ret);
return 0;
}
3.strcat
3.1 The functionality
String append , A two-step , First step : Copy source string , The second step : Attach the copied meta string to the target space “ the last one ”‘\0’ It's about . Returns a pointing to the target space char* The pointer
3.2 The usage function
char * strcat ( char * destination, const char * source );
matters needing attention :
The source string must be in '\0' end , Because it should be used as the end sign of the new string formed after attachment .
The target space must be large enough to be modified , It can hold the contents of the source string .
3.3 Function simulation
// simulation strcat
// String append
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* str1,const char* str2)
{
assert(str1 && str2);
char* ret = str1;
while (*str1 != 0)
{
str1++;
}
while (*str1++ = *str2++)
{
;
}
return ret;
}
int main()
{
char str1[20] = "abcd";
char str2[] = "abc";
char* ret = my_strcat(str1, str2);
printf(ret);
return 0;
}
4.strcmp
4.1 The functionality
String comparison , according to ASCII The code value compares each character of the two strings in turn , After comparing the results , function break. Returns an integer
4.2 The usage function
int strcmp ( const char * str1, const char * str2 );
matters needing attention :
Just compare the string size , Instead of modifying , therefore str1 and str2 All use const modification
str1 Greater than str2, Return is greater than the 0 The number of
str1 be equal to str2, return 0
str1 Less than str2, Back to less than 0 The number of
// This number is determined by the compiler
4.3 Function simulation
// simulation strcmp
#include<stdio.h>
#include<assert.h>
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}// here while You can't make it post ++ Oh , Because in if The next character is compared when
return *str1-*str2;
}
int main()
{
char str1[] = "a";
char str2[] = "b";
int ret = my_strcmp(str1, str2);
printf("%d", ret);
return 0;
}
// This number corresponds to two characters ASCII The difference in value .
For example, ow : Compare ‘a’ and ‘b’ size
'a'==97;'b'==98, So the result is -1;
// Of course, this number can be set by yourself , Similar to piecewise function
Attached with one ASCII surface

5.strncpy
5.1 The functionality
Copy of string with limited length , take source Before num Copy characters to the target space , Returns a pointing to the target space char* The pointer
If the end of the source string is marked ‘\0' Copying num Characters found before , The target uses 0 fill , Until a total of num Characters .
5.2 The usage function
char * strncpy ( char * destination, const char * source, size_t num );
matters needing attention : Same as strcpy;
5.3 Function simulation
// simulation strncpy
// The length is limited , More secure
#include <stdio.h>
#include <assert.h>
char* my_strncpy(char* dest, const char* src, int count)
{
assert(dest && src);
char* temp = dest;
while (count--)
{
*(dest + count) = *(src + count);
}
return temp;
}
int main()
{
char str1[] = "abcdef";
char str2[] = "xyz";
char* ret = my_strncpy(str1, str2,5);
printf("%s", ret);
}
Simulation is not a real substitute ,'\0' After and , There are no supplements 0, For example, in the picture below str1[4] and str1[5] Not at all '\0' But this does not affect subsequent use ;

6.strncat
6.1 The functionality
Strings with limited length are appended , Before the source string num Copy characters to target space , Returns... Pointing to the destination address char* The pointer
6.2 The usage function
char * strncat ( char * destination, const char * source, size_t num );
matters needing attention ; Same as strcat;
6.3 Function simulation
// simulation strncat
// Limited length
#include<stdio.h>
#include<assert.h>
char* my_strncat(char* str1,const char* str2,int count)
{
assert(str1 && str2);
char* temp = str1;
while (*str1 != 0)
{
str1++;
}
while (count--)
{
*(str1+count) = *(str2+count);
}
return temp;
}
int main()
{
char str1[20] = "abcdef";
char str2[] = "xyz";
char* ret = my_strncat(str1, str2,6);
printf("%s", ret);
return 0;
}
7.strncmp
7.1 The functionality
It's just a comparison num Character string function , Returns an integer
7.2 The usage function
int strncmp ( const char * str1, const char * str2, size_t num );
matters needing attention :
And strcmp The only difference is ,strncmp You don't have to compare all the characters
7.3 Function simulation
#include<stdio.h>
#include<assert.h>
int my_strncmp(const char* str1, const char* str2,int count)
{
assert(str1 && str2);
int i;
for (i = 0; i < count; i++)
{
if (*(str1 + i) == *(str2 + i));
if (*str1 == '\0')
{
return 0;
}
}
return *str1 - *str2;
}
int main()
{
char str1[] = "abcedf";
char str2[] = "abcfgh";
int ret = my_strncmp(str1, str2,3);
printf("%d", ret);// The answer is 0 Oh , Jumi ;
return 0;
}
8.strstr
8.1 The functionality
Determine whether it is a substring , Judge str2 Is it str1 The string of .
yes , return str1 in For the first time with str2 Pointer at the same place as the character pointed to
no , Return null pointer ;
such as “ABCD” “BC”,str2 yes str1 The string of , return str1 in Point to B The pointer to , The last thing to print is BCD
8.2 The usage function
char * strstr ( const char *str2, const char * str1);
matters needing attention :
Judging substrings , It only involves the comparison of strings , therefore , All use const modification
8.3 Function simulation
// simulation strstr
// Judging substrings
#include<stdio.h>
#include<assert.h>
#include<string.h>
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
char* s1;
char* s2;
char* cp = str1;
if (*str2 == '\0')
return str1;
while (*cp)
{
s1 = cp;
s2 = str2;
while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2== '\0')
{
return cp;
}
cp++;
}
return NULL;
}
int main()
{
char str1[] = "abcd";
char str2[] = "bc";
char* ret = my_strstr(str1, str2);
if (ret == NULL)
{
printf(" Not substring \n");
}
else
{
printf("%s", ret);//bcd
}
return 0;
}
9.strtok
9.1 The functionality
String segmentation , Eliminate the separator in the string , Returns a pointer to the split string
9.2 The usage function
char * strtok ( char * str, const char * sep );
I feel I don't use much , You can split mailboxes , Split address and so on
10.memcpy
10.1 The functionality
Memory non overlapping copies , hold source Medium num Copy bytes to destination in , Return to point destination The pointer to ;
10.2 The usage function
void * memcpy ( void * destination, const void * source, size_t num );
matters needing attention :
Function encountered '\0' It doesn't stop .
If source and destination There is any overlap , The results of replication are undefined .
The return is void* The pointer Use is up to the programmer .
10.3 Function simulation
// simulation memcopy
// Memory non overlapping copies
#include<stdio.h>
#include<string.h>
#include<assert.h>
void* my_memcopy(void* dest, const void* src, size_t count)
{
assert(dest && src);
void* ret = dest;
while (count--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr1[100] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[100] = { 0 };
int i;
int* p=(int *)my_memcopy(arr2, arr1, 10 * sizeof(int));
for (i = 0; i < 10; i++)
{
printf("%d ", *(p+i));// Can directly arr[i]; To print an array with a pointer, use a loop
}
return 0;
}
Remember not to directly printf(p); This is not char* type
11.memmove
11.1 The functionality
And memcpy The difference is that memory can overlap
11.2 The usage function
void * memmove ( void * destination, const void * source, size_t num )
matters needing attention :
When source and destination Use when there is memory overlap memmove;
11.3 Function simulation
//memmove simulation
#include<stdio.h>
#include<string.h>
#include<assert.h>
void* my_memmove(void* dst, const void* src, size_t count)
{
void* ret = dst;
if (dst <= src || (char*)dst >= ((char*)src + count))
{
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
}
else
{
dst = (char*)dst + count - 1;
src = (char*)src + count - 1;
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst - 1;
src = (char*)src - 1;
}
}
return ret;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int i;
my_memmove(arr+2,arr,16);
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
12.memcmp
Compare by byte , Compare source and destination Of num Bytes
if num Less than the length of both ,memcpy and strncmp Do not have what difference
if num Longer than one of the two , encounter '\0'
strncmy Just stop comparing , and memcpy Will continue to compare , until num Up to bytes
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
contrast strncmp,( personally )memcmp More comprehensive , You can compare both strings and structures .
边栏推荐
- Execjs call
- 【自我救赎的开始】
- AQS之CyclicBarrier源码解析
- mysql-8.0.17-winx64(附加navicat)手动配置版安装
- Leetcode skimming diary sword finger offer II 050. sum of downward path nodes
- [C note] data type and storage
- [哈希表基础知识]
- redis实现分布式锁思路及redission分布式锁主流程分析
- Optimization ideas from ordinary query commodities to highly concurrent query commodities
- 2021-11-10
猜你喜欢

C语言的动态内存管理函数
![[dynamic planning -- the best period series for buying and selling stocks]](/img/90/9060eabc9b9e7f660504806fde282d.png)
[dynamic planning -- the best period series for buying and selling stocks]

Redis cache design and performance optimization
![[basic knowledge of binary tree]](/img/4f/9fc27a30b958af26537c299e150ee9.png)
[basic knowledge of binary tree]

Source code analysis of countdownlatch of AQS

AQS之ReentrantLock源码解析

Explain in detail

Leetcode 刷题日记 剑指 Offer II 053. 二叉搜索树中的中序后继

redis缓存设计与性能优化

关于时间复杂度,你不知道的都在这里
随机推荐
SSAO by computer shader (III)
关于Shader KeyWord的整理
OJ 1089 春运
[c语言]简易通讯录的实现
Mongodb quick start
[PTA----输出全排列]
[哈希表基础知识]
@Postconstruct annotations and useful examples
OJ 1505 fuse
js 变量等于0也等也' '问题
【C语言】动态内存管理
网络通信及TCP/IP协议
Two dimensional array practice: spiral matrix
OJ 1018 报数游戏
2022-07-17 Damon database installation
2022-07-19 Damon database connection instance, execution script, system command
【C笔记】数据类型及存储
mysql索引优化
What is the best and most cost-effective open headset recommended
[PTA----树的遍历]