当前位置:网站首页>[learning notes, dog learning C] string + memory function
[learning notes, dog learning C] string + memory function
2022-07-27 03:18:00 【Jiang Junzhu】
List of articles
- One 、strlen Function and Simulation Implementation
- Two 、 Unlimited length string function
- 3、 ... and 、 Length restricted string function
- Four 、strstr Function and Simulation Implementation
- 5、 ... and 、strtok Function and Simulation Implementation
- 6、 ... and 、strerror Function and Simulation Implementation
- 7、 ... and 、 Memory function
- 8、 ... and 、 Character functions
One 、strlen Function and Simulation Implementation
- Function USES
int main() {
char arr[] = "abc";
int len = strlen(arr);
printf("%d\n", len);
return 0;
}
- Function introduction
String to ’\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 ;
Note that the return value of the function is size_t, It's unsigned .
- Function source code

size_t stay <vcruntime.h> In the definition oftypedef unsigned int size_t;, It's unsigned ;
Receive one char Data of type , use const modification , Ensure that the content pointed to by the pointer cannot be changed by the pointer . - Simulation Implementation
// Counter mode
int my_strlen(const char* str) {
int count = 0;// Counter
assert(str != NULL);// Pointer assertion , Ensure the validity of the pointer
while (*str != '\0') {
count++;
str++;
}
return count;
}
// Cannot create temporary variable counter
int my_strlen(const char * str) {
if(*str == '\0')
return 0;
else
return 1+my_strlen(str+1);
}
// The pointer - The way of the pointer
int my_strlen(char *s) {
char *p = s;
while(*p != ‘\0’ )
p++;
return p-s;
}
int main() {
char arr[] = "abc";
int len = my_strlen(arr);
printf("%d\n", len);
return 0;
}
- And strlen Difference of function
int main() {
// because strlen Returns an unsigned number , So print >
if (strlen("abc") - strlen("abcedf") > 0)
{
printf("strlen >\n");
}
else
{
printf("strlen <\n");
}
// Our simulated function returns a int The type is signed , So print <
// If we want to be with strlen As like as two peas , Then you also need to return an unsigned number
// hold int Change it to size_t
if (my_strlen("abc") - my_strlen("abcedf") > 0)
{
printf("my_strlen >\n");
}
else
{
printf("my_strlen <\n");
}
return 0;
}
Two 、 Unlimited length string function
1、strcpy Function and Simulation Implementation
- Function USES
int main() {
char arr[20] = {
0 };
strcpy(arr, "hello");
printf("%s\n", arr);
return 0;
}
- Function introduction
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 .
- Function source code

destination It's a goal , in other words destination Put the replaced character here , That is, the target character .source It means source , Namely source Put replacement characters here , That is, the source character . therefore strcpy Receive two parameters , The first parameter is the character to be replaced , The second parameter is the replacement character ; - Simulation Implementation
char* my_strcpy(char* dest, char* src) {
while (*dest++ = *src++) {
; }
}
int main() {
char arr[20] = {
0 };
my_strcpy(arr, "hello");
printf("%s\n", arr);
return 0;
}
2、strcat Function and Simulation Implementation
- Function USES
int main() {
char arr1[20] = "hello";
char arr2[] = "world";
strcat(arr1, arr2);// String append ( Connect )
printf("%s\n", arr1);
return 0;
}
- Function introduction
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 ;
strcat Functions cannot append themselves .![]()
The original string will find the first of the target string \0, from \0 Start adding .
If you add yourself , It will lead to missing \0, Make the program unable to end .
- Function source code

Receive parameters and strcpy It's the same . - Simulation Implementation
char* my_strcat(char* dest, const char* str) {
char* ret = dest;
assert(dest && str);// Assertion , Make sure the pointer is valid
// Find... In the target string \0
while (*dest) {
dest++;
}
// Append source string
while (*dest++ = *str++) {
; }
return ret;//strcat Returns the starting address of the target space , We also return the starting address of the target space
}
int main() {
char arr1[20] = "hello";
char arr2[] = "world";
my_strcat(arr1, arr2);// String append ( Connect )
printf("%s\n", arr1);
return 0;
}
3、strcmp Function and Simulation Implementation
- Function USES
int main() {
printf("%d\n", strcmp("abc", "abb"));
printf("%d\n", strcmp("abc", "abc"));
printf("%d\n", strcmp("abb", "abc"));
return 0;
}
- Function introduction
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 .
- Function source code

- Simulation Implementation
int my_strcmp(const char* s1, const char* s2) {
assert(s1 && s2);
while (*s1 == *s2) {
s1++;
s2++;
if ('\0' == *s1 || '\0' == *s2) {
break;
}
}
return *s1 - *s2;
}
int main() {
printf("%d\n", my_strcmp("abc", "abb"));
printf("%d\n", my_strcmp("abc", "abc"));
printf("%d\n", my_strcmp("abb", "abc"));
return 0;
}
3、 ... and 、 Length restricted string function
1、strncpy Function and Simulation Implementation
- Function USES
int main() {
char arr1[20] = "abcdef";
char arr2[] = "qwer";
printf("%s\n", strncpy(arr1, arr2, 2));
return 0;
}
- Function introduction
Copy n 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 .
- Function source code

It is better than strcpy One more. Count Counter , Used to determine how many characters are copied from the original string to the target space . So it is called the length limited string function , and strcpy It is called string function with unlimited length . - Simulation Implementation
char* my_strncpy(char* dest, char* src, int count) {
while (*dest++ = *src++) {
count--;
}
int i = 0;
for (i = 0; i < count - 1; i++) {
*dest++ = '\0';
}
}
int main() {
char arr1[20] = "abcdefdef";
char arr2[] = "qwer";
my_strncpy(arr1, arr2, 6);
printf("%s\n", arr1);
return 0;
}
2、strncat Function and Simulation Implementation
- Function USES
int main() {
char arr1[20] = "abcd";
char arr2[] = "efgh";
strncat(arr1, arr2, 2);
printf("%s", arr1);
return 0;
}
- Function introduction
Put the source string n Characters are appended to the target space , And add a terminated null character at the end ;
If the length of the source string is less than n individual , Then only the original string including the terminating null character is appended to the target space .
- Function source code

- Simulation Implementation
char* my_strncat(char* dest, const char* str, int count) {
char* ret = dest;
assert(dest && str);// Assertion , Make sure the pointer is valid
// Find... In the target string \0
while (*dest) {
dest++;
}
int i = 0;
for (i = 0; i < count; i++) {
if ('\0' == *str) {
break;
}
*dest++ = *str++;
}
*dest++ = '\0';
return ret;
}
int main() {
char arr1[20] = "abcd";
char arr2[] = "efgh";
my_strncat(arr1, arr2, 2);
printf("%s", arr1);
return 0;
}
3、strncmp Function and Simulation Implementation
- Function USES
int main() {
char* p = "abcde";
char* q = "abbc";
int ret = strncmp(p, q, 4);
printf("%d\n", ret);
return 0;
}
- Function introduction
Compare to a different character or the end of a string or n Compare all the characters .
- Function source code

- Simulation Implementation
int my_strncmp(const char* s1, const char* s2, int count) {
assert(s1 && s2);
int i = 0;
for (i = 0; i < count; i++) {
if (*s1 != *s2) {
break;
}
s1++;
s2++;
if (i == count - 1 || '\0' == *s1 || '\0' == *s2) {
return 0;
}
}
return *s1 - *s2;
}
int main() {
char* p = "abcde";
char* q = "abc";
int ret = my_strncmp(p, q, 4);
printf("%d\n", ret);
return 0;
}
Four 、strstr Function and Simulation Implementation
- Function USES
int main() {
char arr1[20] = "abbbdefgh";
char arr2[] = "bbd";
char* ret = strstr(arr1, arr2);
if (NULL == ret) {
printf(" Did not find \n");
}
else {
printf(" eureka :%s\n", arr1);
}
return 0;
}
- Function introduction
If str2 yes str1 Subset , Then return to str1 Detected with str2 Address with the same value , If str2 No str1 Part of , Return null pointer .
- Function source code

- Simulation Implementation
char* my_strstr(const char* str1, const char* str2) {
char* cp = (char*)str1;
char* s1, * s2;
if (!*str2)
return((char*)str1);
while (*cp)
{
s1 = cp;
s2 = (char*)str2;
while (*s1 && *s2 && !(*s1 - *s2))
s1++, s2++;
if (!*s2)
return(cp);
cp++;
}
return(NULL);
}
int main() {
char arr1[20] = "abbbdefgh";
char arr2[] = "bbd";
char* ret = my_strstr(arr1, arr2);
if (NULL == ret) {
printf(" Did not find \n");
}
else {
printf(" eureka :%s\n", arr1);
}
return 0;
}
5、 ... and 、strtok Function and Simulation Implementation
- Function USES
int main() {
char arr[] = "[email protected]";
char* p = "[email protected]";
char tmp[20] = {
0 };
strcpy(tmp, arr);
char* ret = NULL;
for (ret = strtok(tmp, p); ret != NULL; ret = strtok(NULL, p)) {
printf("%s\n", ret);
}
return 0;
}
- Function introduction
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 mark separated by one or more separators in a string ;
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 cut by the function is usually a temporary copy and can be modified );
strtok The first argument of the function is not NULL , Function will find str The first mark in ,strtok Function will hold its position in the string ;
strtok The first argument to the function is NULL , The function will start at the same position in the string that is saved , Find next tag ;
If there are no more tags in the string , Then return to NULL The pointer .
- Function source code

- Simulation Implementation
I'm sorry , I don't deserve it. .
6、 ... and 、strerror Function and Simulation Implementation
- Function USES
// When using function libraries
// Call to library function failed , Will set the error code
int main() {
// If the file fails to open, a NULL The pointer
FILE* pf = fopen("test.txt", "r");
if (NULL == pf) {
printf("%s\n", strerror(errno));
return 1;
}
// Close file
fclose(pf);
pf = NULL;
return 0;
}
- Function introduction
Return error code , The corresponding error message .
7、 ... and 、 Memory function
1、memcpy Function and Simulation Implementation
- Function USES
int main() {
int arr1[10] = {
0 };
int arr2[10] = {
1,2,3,4,5,6,7,8,9,10 };
memcpy(arr1, arr2, 20);
return 0;
}
- Function introduction
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 ;
If source and destination There is any overlap , The results of replication are undefined .
Function source code

Simulation Implementation
void* my_memcpy(void* dest, void* src, size_t num) {
assert(dest && src);
void* ret = dest;
while (num--) {
*(char*)dest = *(char*)src;
dest =(char*)dest + 1;
src = (char*)src + 1;
}
}
int main() {
int arr1[10] = {
0 };
int arr2[10] = {
1,2,3,4,5,6,7,8,9,10 };
my_memcpy(arr1, arr2, 20);
return 0;
}
2、memmove Function and Simulation Implementation
- Function USES
int main() {
int arr1[10] = {
1,2,3,4,5,6,7,8,9,10 };
memmove(arr1 + 2, arr1, 20);
return 0;
}
- Function introduction
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 , You have to use memmove Function processing .
Function source code
Simulation Implementation
void* my_memmove(void* dest, const void* src, size_t num) {
assert(dest && src);
void* ret = dest;
if (dest < src) {
while (num--) {
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else {
while (num--) {
*((char*)dest + num) = *((char*)src + num);
}
}
return ret;
}
int main() {
int arr1[10] = {
1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr1 + 2, arr1, 20);
return 0;
}
3、memcmp function
- Function USES
int main() {
float arr1[] = {
1.0,2.0,3.0,4.0 };
float arr2[] = {
1.0, 3.0 };
int ret = memcmp(arr1, arr2, 8);
printf("%d\n", ret);
return 0;
}
- Function introduction
Compare from ptr1 and ptr2 The pointer starts with num Bytes ;
The first memory is larger than the second memory , Return greater than 0 The number of ;
The first memory is equal to the second memory , Then return to 0;
The first memory is smaller than the second memory , Then return less than 0 The number of .
4、memset function
- Function USES
int main() {
int arr[10] = {
0 };
memset(arr, 1, 20);
return 0;
}
- Function introduction
Set memory in bytes .

8、 ... and 、 Character functions
1、 Character classification function
| 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 a~f, Capital A~F |
| islower | Lowercase letters a~z |
| isupper | Capital A~Z |
| isalpha | Letter a~z or A~Z |
| isalnum | Letters or numbers ,a~z,A~Z,0~9 |
| ispunct | Punctuation , Any graphic character that is not a number or letter ( Printable ) |
| isgraph | Any graphic character |
| isprint | Any printable character , Including graphic characters and white space characters |
2、 Character conversion function
int tolower ( int c );// Convert upper case letters to lower case letters
int toupper ( int c );// Convert lowercase letters to uppercase letters
边栏推荐
- CAS deployment and successful login jump address
- 记录一次,php程序访问系统文件访问错误的问题
- 水仙花数(DAY 78)
- OC-消息机制
- 子模块cache缓存失效
- sqlserver select * 能不能排除某个字段
- Common questions and answers of software testing interview (divergent thinking, interface, performance, concept,)
- 基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)
- [SQL简单题] LeetCode 627. 变更性别
- Use the most primitive method to manually implement the common 20 array methods
猜你喜欢

Bulk copy baby upload prompt garbled, how to solve?
Common questions and answers of software testing interview (divergent thinking, interface, performance, concept,)
![[paper]PointLaneNet论文浅析](/img/f6/8001be4f90fe15100e0295de02491f.png)
[paper]PointLaneNet论文浅析

记录一次,php程序访问系统文件访问错误的问题
The most complete basic knowledge of software testing in the whole network (a must for beginners)

Compile and use protobuf Library in vs2019

Inftnews | "traffic + experience" white lining e Digital Fashion Festival leads the new changes of digital fashion

Hcip 13th day notes

浅浅梳理一下双轴快排(DualPivotQuickSort)

Worthington果胶酶的特性及测定方案
随机推荐
周全的照护 解析LYRIQ锐歌电池安全设计
Naive Bayes -- Document Classification
浅浅梳理一下双轴快排(DualPivotQuickSort)
How to use devaxpress WPF to create the first MVVM application in winui?
将幕布文章OPML转换为Markdown的方法
力扣(LeetCode)207. 课程表(2022.07.26)
[paper]PointLaneNet论文浅析
Hcip day 14 notes
How to visit the latest version of burpsuite pro in vain
我的爬虫笔记(七) 通过爬虫实现blog访问量+1
185. All employees with the top three highest wages in the Department (mandatory)
Baidu cloud face recognition
DNS记录类型及相关名词解释
vector 转 svg 方法
[动态规划中等题] LeetCode 198. 打家劫舍 740. 删除并获得点数
[二分查找简单题] LeetCode 35. 搜索插入位置,69. x 的平方根,367. 有效的完全平方数,441. 排列硬币
sqlserver select * 能不能排除某个字段
Comprehensive care analysis lyriq Ruige battery safety design
软件测试面试常见问题及答案(发散思维、接口、性能、概念、)
Abbkine AbFluor 488 细胞凋亡检测试剂盒特点及实验建议

