preface
**This article introduces character functions and string functions, from 0 to proficient, how to reference to how to simulate the implementation.
In C language, we often operate on strings, so we can call many library functions directly. However, if we want to deeply understand C language, we need to know how to realize its principle. Don't be afraid I'll come!
**
Warm tip: some codes don't display header files. Irons lead files by themselves
1, Is there a string type in C?
**
-Answer: No, strings are usually placed in string constants and string arrays; String constant: cannot be changed
Look at this string, it just saves the address of the first letter of the string in p, and uses the string copy function to copy str to p. it is wrong, and the program hangs up directly
**
2, strlen find string length function;
Introduction:
1. The string has' \ 0 'as the end flag. The strlen function returns the number of characters before' \ 0 'in the string (excluding' \ 0 ')
2. The length of the returned value string. The function parameter is a pointer of char type. const indicates that the string cannot be modified. const is added for insurance, because you need a length to change what people do, right? The return type is size_t, which means that the returned value is an unsigned number, because the length of your string cannot be negative - but there is a disadvantage End, look at the code below*
```c #include <stdio.h> #include<string.h> int main(){ if (strlen("abc") - strlen("abcde")>0) { printf(">"); } else { printf("<=\n"); } return 0; }
Because the return value is an unsigned number, unsigned number - unsigned number = = unsigned number, try it yourself. Note: be sure to index the header file < string... H > otherwise it will be incorrect
1. The counter method is simulated to achieve strlen
//Simulated implementation of strlen #include<assert.h> int my_strlen(const char*str){ int count = 0;//Counter assert(str!=NULL); while (*str != '\0'){ str++; count++;//*str is not a '\ 0' counter++ } return count; } int main(){ char arr[] = "abceds"; int ret = my_strlen(arr); printf("%d\n", ret); return 0; }
2. The recursive method implements strlen without using counters
int my_strlen(char *str){ assert(str!=NULL); if (*str != '\0'){ return 1 + my_strlen(str +1); }//If the if statement comes in this time, it must not be '\ 0', so + 1, when calling the function, str+1 points to the next element, and then come in, //Last come in '\ 0'! = '\ 0' false return 0 return 0; } int main(){ char arr[] = "abceds"; int ret = my_strlen(arr); printf("%d\n", ret); return 0; }
Take a brief look at the principle
3. The pointer pointer method simulates the implementation of strlen without counters
int my_strlen(char *str){ char *start = str;//Start address to start pointer while (*str){ str++; } return str-start;//End address - first address } int main(){ char arr[] = "abcdef"; int ret = my_strlen(arr); printf("%d\n", ret); return 0; }
Here, you should understand that the pointer obtains the number of elements in the middle. See the principle:
3, strcpy string copy function;
Introduction:
**First look at the description:
1. The return destination operand of the function. Look at the first figure. Why use const? Because you copy the function, the source operand does not need to be modified, and the destination operand needs to be modified.
2. Look at the return value. char * indicates that the return is the first address of the destination operand.
The source string must end with '\ 0'.
The '\ 0' in the source string will be copied to the destination space.
The destination space must be large enough to hold the source string. The destination space must be variable.
**
Simulation implementation strcpy
char* my_strcpy(char* str1, const char * str2){ assert(str1&&str2); char* ret = str1; //Post + +, use first and add later, assign to str1 one by one, and finally '\ 0' is assigned. The cycle ends while (*str1++ = *str2++){ ; } return ret; } int main(){ char arr1[10] = "abcdef"; char arr2[] = "abc"; //The return type is the address value, which is received with a pointer char *str =my_strcpy(arr1, arr2); printf("%s\n", str); return 0; }
**Simple principle explanation:
**
4, strcat string concatenation function
Introduction:
**1. Wow, the return value and parameters are the same as the previous one. Oh, const modifies the source operand, because you connect the source operand to the destination operand, and the source operand does not need to be changed
2. The source string must end with '\ 0'. This also means that '\ 0' must be connected,
The target space must be large enough to accommodate the contents of the source string.
The target space must be modifiable.
**
Simulated implementation of strcat
char* my_strcat(char* str1,const char* str2){ //1. Find the backslash 0 of the destination operand //2. Realize the connection of two characters assert(str1&&str2); char* ret = str1;//The first address of str1 is temporarily stored because the address before str1 has not been changed is to be returned while (*str1){ str1++; }//The end condition is to end when \ 0 is found, while (*str1++ = *str2++){ ;// } return ret; } int main(){ char arr1[20] = "peichao "; char arr2[] = "dongdong"; int *str=my_strcat(arr1, arr2); printf("%s\n", str); return 0; }
Simple implementation principle:
5, strcmp string comparison function;
Introduction:
***1. Both parameters are char *, and the addresses of the two strings are passed, and both are modified by const, because it is relatively unnecessary to modify the two strings, plus const security***
2. The return value is int. as shown in the figure, string 1 < string 2 returns a number less than 0
String 1 > string 2, returns a number greater than 0
String 1 = string 2, return 0
**See how to reference:
The corresponding comparison, a and a are equal than the next pair
**
Simulated implementation of strcmp
int my_strcmp(char *str1, char*str2){ while (*str1 == *str2){ assert(str1&&str2); str1++;//If the two characters here are equal, + +, compare the next pair of characters str2++; if (*str1 == '\0')//If one of the characters is' \ 0 ', it means that the two characters are equal return 0; } if (*str1 > *str2){ return 1; } else return -1; } int main(){ char arr1[10] = "aaec"; char arr2[10] = "aaa"; int ret=my_strcmp(arr1, arr2); printf("%d\n", ret); }
**Principle explanation:
**
>The above is a function that does not limit the len gt h of the string, such as strcpy: I don't care how many characters you want to copy, as long as you call me, I just copy them all to the destination operand
Next, we introduce library functions that limit the length of strings
6, strncpy copy function that limits the length of a string;
Introduction:
1. There are three parameters. The first and second parameters are char, and the address of the string is passed. The third parameter is the unsigned number, the number of characters you copy
2. The return value is char, and the return value is the address of the destination operand
3. Next, let's see how this count is used. It is greater than the source operand and less than the length of the source operand. How can it be copied**
Less than
Greater than
Note: if the number of strings you want to copy is greater than the number of strings, the remaining default copy is' \ 0 '
Simulation implementation strncpy
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<string.h> #include<assert.h> char* my_strncpy(char *str1, char *str2, int k){ assert(str1&&str2);//Avoid null pointers; char* ret = str1;//Because it is necessary to return to the initial address for temporary storage; while (k--){//Control the number of copies *str1 = *str2;//Replace the first character with the first character, str1++; str2++; } return ret; } int main(){ char arr1[20] = "abcd"; char arr2[] = "aa"; //strncpy(arr1, arr2, 2); char *str = my_strncpy(arr1, arr2, 2); printf("%s\n", str); return 0; }
7, strncat string concatenation function with limited length
Introduction:
1. Both operands are char, and the third is the number you want to connect. The return type is char, that is, the address of the destination operand (the address of the first parameter),
**
How to reference & & what to pay attention to:
Simulated implementation of strncat
char* my_strncat(char* str1, const char* str2, int k){ assert(str1&&str2); char* ret = str1; while (*str1){ str1++; }//Jump out here and find \ 0; while (k--){ if ((*str1++ = *str2++) == '\0') return ret; } *str1 = '\0'; return ret; } int main(){ char arr1[20] = "peichao\0"; char arr2[] = "dongdong"; char* ret=my_strncat(arr1, arr2, 10); printf("%s\n", ret); return 0; }
Explain the set number of characters to be connected. If it is greater than this number of characters:
**
Explain the set number of characters to be connected. If it is less than this number of characters:**
8, strncmp string comparison function with limited length;
Introduction:
**1. The two formal parameters are modified by const. For comparison, you don't need to modify them. The third is the number you compare
2. It is compared that another character is different, or a string ends, or num characters are all compared**
How to call:
Simulated implementation of strncmp
int my_strncmp(char *str1, char *str2, int k){ while (k-- && (*str1 == *str2)){//Cycle condition: k==0 ends; * str1! = * str2 ends str1++; str2++; if (*str1 =="\0" || k == 0){//If num or a string is compared, 0 is returned return 0; } return *str1 - *str2;//The end of the loop will jump to this. Subtract the two characters to see their positive and negative } } int main(){ char arr1[] = "agb"; char arr2[] = "azb"; printf("%d\n",my_strncmp(arr1, arr2,3)); } // The two strings are different, or the character is compared, or num strings are compared
9, strstr function to find substrings
Introduction:
*1. Both parameters are char. If parameter 1 contains parameter 2, the return value is the address currently pointed to by the first parameter, otherwise the NULL pointer is returned
2. The parameters are modified by const, which is safer
~Draw a picture and have a look. Good understanding:
**
Simulation implementation str
#include<stdio.h> #include<string.h> #include<assert.h> char* my_strstr(const char* str1, const char* str2){ assert(str1&&str2); char* s1 = NULL; char* s2 = NULL; char* cp = (char*)str1;//The initial position of the string if (*str2 == '\0'){ return (char*)str1; } while (*cp){ s1=cp; s2 = str2; while (*s1!='\0'&&*s2!='\0'&&*s1 == *s2){ s1++; s2++; } if (*s2 == '\0'){ return cp; } cp++; } return NULL;//After a loop, no substring is found and NULL is returned } int main(){ char arr1[] = "abcwfqageg"; char arr2[] = "bbc"; char* ret=my_strstr(arr1, arr2); if (ret == NULL){ printf("Can't find\n"); } else printf("eureka:%s\n", ret); return 0; }
Explanation:
Let's take a look at the general step and explain it in detail below:
Step 1:
Step 2:
Step 3:
10, strtok string (SMART) cut and print function
Introduction and reference:
char * strtok ( char * str, const char * sep );
The sep parameter is a string that defines the set of characters used as delimiters
For example:
The first parameter specifies a string that contains 0 or more tags separated by one or more separators in the sep string
The strtok function finds the next tag in str, ends it with \ 0, and returns a pointer to this tag. (Note: the strtok function will change the string to be manipulated, so the string segmented by the strtok function is generally a temporary copy and can be modified.)
The first parameter of the strtok function is not NULL. The function will find the first tag in str, and the strtok function will save its position in the string
The first parameter of strtok function is NULL. The function will start at the position saved in the same string to find the next tag.
If there are no more tags in the string, a NULL pointer is returned
If the tag is not found, the null pointer is returned, that is, the search is completed
**This library function is not very commonly used. It mainly knows how to call it. It can be called three times in the last screenshot,
But if there are 100 separators, will it be called 100 times? Obviously not. Let's take a look at a simple method:
**
int main(){ char arr1[20] = "abc.aid#cbub"; char sep[] = ".#"; char str[30] = { 0 }; strcpy(str, arr1);//Temporary copy char* ret=NULL; for (ret = strtok(str, sep); ret != NULL; ret = strtok(NULL, sep)){ printf("%s\n", ret); } return 0; }
This function call cuts the string. To call the required number of times, you remember
For the first time, parameter 1 is the cut string. For each subsequent call, parameter 1 is NULL
Parameter 2, unchanged every time
11, strerror function that returns error information
Introduction:
char * strerror ( int errnum );
Return the error code and the corresponding error information
#Include < errno. H > / / this header file must be included int main(){ FILE* pf = fopen("test.txt", "r"); if (pf == NULL){ printf("%s\n", strerror(errno)); return 1; } //Close file: fclose(pf); pf = NULL; return 0; }
**This paper introduces a function to print errors directly: perror**
The header file #include < stdio. H > must be quoted
12, memcpy memory copy function
Introduction:
#include<stdio.h> #include<string.h> #include<assert.h> int main(){ int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int arr2[10] = { 0 };//Copy the five elements of arr1 to arr2 strcpy(arr1, arr2);//Will this work? Of course not, //Char * strcpy (char * DeST, const char * SRC) strcpy is such a return type, which is an integer array //What should I do? Next, let's look at the memory copy function return 0; }
1. The types of parameter 1 and parameter 2 are void, because the library function doesn't know what type you copy.
2. The third parameter is size_ T returns an unsigned number. The first two parameters are pointers without specific types, so the third parameter indicates how many bytes you copy. The return type is viod**
memcpy Simulation Implementation
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<string.h> #include<assert.h> void* my_memcpy(void* dest, void* src,size_t num){ assert(dest&&src); void* ret = dest;//Initial address staging while (num--){ *(char*)dest = *(char*)src; dest = (char*)dest + 1; src = (char*)src + 1;//Pointer + 1. Because our data is int, we need to convert it to the pointer of char *, and then + 1. char*+1 skips a byte } return ret; } int main(){ int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int arr2[10] = { 0 };//Copy the first five elements my_memcpy(arr2, arr1, 20);//Copy five elements, 5 * 4 = 20 bytes of int type int i = 0; for (i = 0; i < 10; i++){ printf("%d ", arr2[i]); } return 0; }
Explanation:
Look at the figure below. memcpy cannot copy the memory overlap area:
This leads to another memory function memmove
13, memmove memory move function
Introduction:
1. The parameters and return types of memcpy and memcpy are the same
It can copy the memory overlapping area
Implementation idea:
memmove Simulation Implementation
void* my_memmove(void* dest, void* src, size_t num){ assert(dest&&src); void* ret = dest;//Temporary first address if (src > dest){ //Front - > rear while (num--){ *(char*)dest = *(char*)src; dest = (char*)dest + 1;//When the destination pointer is cast to character + 1, a byte is skipped //Because void * you don't know what type is passed. First convert it to char *, a byte by byte operation src = (char*)src + 1; } } else { //Rear - > front 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 }; //int arr2[10] = { 0 };// Copy the first five elements my_memmove(arr1, arr1+3, 20);//Copy five elements, 5 * 4 = 20 bytes of int type }
Explanation:
14, memcmp -- memory comparison function
Introduction:
1. The two parameter types are void and are modified by const, because they only need not be modified. The third parameter is an unsigned number and the return type is int.
2. The return type is the same as strncmp. You can see the detailed introduction of strncmp*
//memcmp -- memory comparison function int main(){ int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int arr2[] = { 1, 2, 3, 5 }; int ret = memcmp(arr1, arr2, 16); printf("%d\n", ret); return 0; }
Warm tip: This is based on the ratio of bytes. 16 bytes are exactly 4 elements, and float accounts for 4 bytes!!!
15, memset -- memory setting function
Explanation:
The meaning of this function is to set the second parameter to memory and return to the first address of dest with the type of void in bytes*
int main(){ int arr1[10] = { 0 }; memset(arr1, 1, 20); return 0; }
End, tietie, remember Sanlian ha. It's not easy to make. Learn from each other