C The processing of characters and strings is very frequent in language , however ,C The language itself has no string type , Strings are usually placed in constant strings or character arrays .

Constant string is applicable to string functions that do not modify it .

1. Introduction of string function and Its Simulation Implementation

1.strlen

size_t strlen (const char* str);

1. String is used '\0' As an end sign ,strlen Function returns yes, from the given position to '\0' Number of characters between , barring '\0';

2. The string pointed to by the parameter must be '\0' end , Otherwise, cross-border visits may occur ;

3.strln The return value of the function is size_t, Is an unsigned integer ;

use :
#include <stdio.h> #include <string.h> int main() { char* arr = "abcdef"; char
arr2[] = "abcdefgh"; int len = strlen(arr); int len2 = strlen(arr2);
printf("%d\n", len); printf("%d\n", len2); return 0; }
Remember to introduce the header file

Pay attention to the following situations , because strlen The return value type of is size_t of , So the final result is a large number , instead of -2

Next, let's simulate and realize it strlen function

Simulation Implementation :

1. Method of counter :
#include <assert.h> size_t my_strlen(const char* str) { assert(str); size_t
count = 0; while (*str++) { count++; } return count; }
2. Recursive method :
#include <assert.h> size_t my_strlen(const char* str) { assert(str); if (*str
== '\0') { return 0; } return 1 + my_strlen(++str); }
3. Pointer - Pointer method :
#include <assert.h> size_t my_strlen(const char* str) { assert(str); const
char* p = str; while (*str) { str++; } return str - p; }
2.strcpy

char* strcpy(char* destination, const char* source);

1. The source string must begin with '\0' end ;

2. strcpy The function will '\0' Copy to target space ;

3. The target space must be large enough , To ensure that the source string can be placed , Otherwise, cross-border visits may occur ;

4. The target space must be changeable , If it is a constant string, it cannot be changed ;
int main() { char* str1 = "abcdef"; char* str2 = "abcde"; char* ret =
strcpy(str1, str2); printf("%s\n", ret); return 0; }
Like this ,str1 The string pointed to cannot be changed

use :

strcpy The return value is char* Type , In order to realize chain access , That is, the return value of one function is used as the parameter of another function .

as :
int main() { char arr1[] = "qwertyuiop"; char arr2[] = "abc"; printf("%s\n",
strcpy(arr1, arr2)); return 0; }
Simulation Implementation :
char* my_strcpy(char* dest, const char* src) { assert(dest && src); char* cur
= dest; while (*src) { *dest = *src; dest++; src++; } *dest = *src; return cur;
}
Code can be simplified :
char* my_strcpy(char* dest, const char* src) { assert(dest && src); char* cur
= dest; while (*dest++ = *src++) { ; } return cur; }
3.strcat

char* strcat(char* destination, const char* source);

 1. The source string must begin with '\0' end ;

2. The target space must be large enough , Can accommodate the contents of the source string ‘

3. The target space must be changeable ;

use :

Simulation Implementation :

From the target string's '\0' Start appending source string at position
char* my_strcat(char* dest, const char* src) { assert(dest && src); char* cur
= dest; while (*dest) { dest++; } while (*dest++ = *src++) { ; } return cur; }
4.strcmp

int strcmp(const char* str1, const char* str2);

Compare from the given character position of two strings , If the characters in the corresponding position are the same , Then continue to compare the next pair of characters , Until I met '\0' Or two characters are different ;

Standard provisions :

1. The first string is larger than the second string , Then return greater than 0 Number of ;

2. The first string is equal to the second string , Then return 0;

3. The first string is smaller than the second string , Then return less than 0 Number of ;

use :

stay VS In compiler ,strcmp Only return -1,0,1 Three numbers .

Simulation Implementation :
int my_strcmp(const char* str1, const char* str2) { assert(str1 && str2);
while (*str1 == *str2 && *str1 != '\0') { str1++; str2++; } if (*str1 > *str2)
{ return 1; } else if (*str1 < *str2) { return -1; } else { return 0; } }
 5.strncpy

char* strncpy(char* destination, const char* source, size_t num);

1. Copy from source string num Characters to target space ;

2. If the number of source strings is less than num, After copying the source string , Append after target '\0', Until the total number of characters reaches num Until ;

use :

Simulation Implementation :
char* my_strncpy(char* dest, const char* src, size_t num) { assert(dest &&
src); size_t len = strlen(src); if (num <= len) { int i = 0; for (i = 0; i <
num; i++) { *(dest + i) = *(src + i); } } else { int i = 0; for (i = 0; i <
len; i++) { *(dest + i) = *(src + i); } for (; i < num; i++) { *(dest + i) =
'\0'; } } return dest; }
6.strncat

char* strncat(char* destination, const char* source, size_t num);

use :

 

  Simulation Implementation :
char* my_strncat(char* dest, const char* src, size_t num) { assert(dest &&
src); char* cur = dest; while (*dest) { dest++; } size_t len = strlen(src); if
(num < len) { int i = 0; for (i = 0; i < num; i++) { *(dest + i) = *(src + i);
} *(dest + i) = '\0'; } else { while (*dest++ = *src++) { ; } } return cur; }
7.strncmp

int strncmp(const char* str1, const char* str2, size_t num);

use :

  Simulation Implementation :
int my_strncmp(const char* str1, const char* str2, size_t num) { assert(str1
&& str2); size_t i = 0; while (*str1 == *str2 && *str1 != '\0' && i < num - 1)
{ str1++; str2++; i++; } if (*str1 > *str2) { return 1; } else if (*str1 <
*str2) { return -1; } else { return 0; } }

The internal implementation method of the function is to compare the size of two characters , If it is the same, the pointer will go back one character size , If num If the first two characters are the same , The last is to compare num For the size of characters , So judgment statement while
(*str1 == *str2 && *str1 != '\0' && i < num - 1) in num want -1.

8.strstr

char* strstr(const char* str1, const char* str2);

 str1 Is the searched string ,str2 For the substring to be retrieved , If in str1 Found in str2, Then return str1 Found in str2 Address of the starting position of the time , If str1 Not found in str2, Then return a null pointer .

use :

  Simulation Implementation :

thinking : Use one cur Pointer pointing str1 First character of , Then take another one s1 The pointer follows cur Pointer , use s2 Pointer to point str2 First character of , When cur When pointing to the first character , take s1 To sum the characters pointed to s2 Compare the characters pointed to by the pointer , If it's different , Then let cur Pointer +1,s1 and cur equally , When *s1 and *s2 At the same time , Give Way s1 and s2 Walk back at the same time , Continue comparing characters , If it's always the same , Then it will appear 3 Cases , The first is str1 The string has arrived '\0' The location of , however str2 Not finished yet , Then exit at this time s1 and s2 Increasing cycle ,cur+1,s1 Back to this time cur+1 Location of ,s2 Also back to str2 Actually, the position of characters , Start matching the same characters again , But if that happens , Big probability will be different , Section 2 Cases , namely s1 and s2 Go straight back , until s2 The character pointed to is '\0', So at this time ,str2 It has been traversed , explain str2 yes str1 Substring of , Then it will also exit the cycle , Judge next *s2 Yes no '\0', If yes, take this time cur Return as return value . Section 3 In this case, the previous string is the same , Difference in the middle , Then it will also exit the cycle , Give Way cur+1, Then put s1 Position of fallback to cur Location of ,s2 The position of also falls back to str2 Position of the starting string , Restart matching .
char* my_strstr(const char* str1, const char* str2) { assert(str1 && str2);
const char* s1 = str1; const char* s2 = str2; const char* cur = str1; while
(*cur) { s1 = cur; s2 = str2; while (*s1 && *s2 && (* s1 == *s2)) { s1++; s2++;
} if (*s2 == '\0') { return (char*)cur; } cur++; } return NULL; }
9.strtok

char* strtok(char* str, const char* sep);

1.sep Parameter is a string , Defines the set of characters used as delimiters

2. First parameter str Is a string , It contains 0 One or more in sep Characters existing in the string as separators are used as markers

3.strtok Function will be in str Next tag found in , And use it '\0' ending , Returns a pointer to this tag .strtok Function will change the string being manipulated , So in use strtok Temporary copied strings are generally used when splitting strings , And the string can be changed .

4.strtok The first flag of the function is not NULL, Function will find str First tag in ,strtok Function will save the position of this tag in the string .

5.strtok The first parameter of the function is NULL, The function will start at the location saved in the same string , Find next tag .

6. If there are no more tags in the string , Null pointer is returned

use :

strtok Function will return the first character address of the split string , We use a cycle , You can print out the strings you want to split in turn
#include <stdio.h> #include <string.h> int main() { char* arr =
"0zhangsan@new.net."; char buff[30]; strcpy(buff, arr); char* sep = "@.0";
char* ret = NULL; for (ret = strtok(buff, sep); ret != NULL; ret = strtok(NULL,
sep)) { printf("%s\n", ret); } return 0; }
10.strerror

char* strerror(int errnum);

strerror It is used to return the error information corresponding to the error code , Sometimes it happens when you surf the Internet 404 Is the error code . 

use :

 

strerror The first character address of the corresponding error message will be returned

11.memcpy

void* memcpy(void* destination, const void* source, size_t num);

1.memcpy Will from source The starting position of starts to copy backwards num Bytes of data to memcpy Memory location of

2. This function encountered '\0' It doesn't stop when

3. If source and destination By any overlap , The results of replication are undefined

use :

  Simulation Implementation :
void* my_memcpy(void* dest, const 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; } return ret; }
This may happen if you copy in the same space :

  This is because the data is copied from front to back, byte by byte , The later data to be copied will be overwritten by the previous data , Causing the copied data to change , and visual
studio This compiler will memcpy The function of has been realized to and memmove The function of is almost the same , So if you use the memcpy To copy in the same space , This will not happen .

 12.memmove

void* memmove(void* destination, const void* source, size_t num); 

1. and memcpy The difference is that the source memory block and the target memory block can overlap , If the source space and target space overlap , You can pass memcpy Function

use :

  Simulation Implementation :

thinking :

There are two cases when two memory spaces overlap :

  First kind , If src stay dest In front of , Then copy the data from the back to the front , First 5 Copy to 8 Location of , Zaijiang 4 Copy to 7 Location of , And so on .

  The second kind , When src again dest Behind , Then copy the data from front to back , First 6 Copy to 4 Location of , Zaijiang 7 Copy to 5 Location of , And so on .

And if the two memory spaces do not overlap , You can copy from front to back or from back to front .

code :
void* my_memmove(void* dest, const void* src, size_t num) { //stc stay dest In front of if
(src < dest) { while (num--) { *((char*)dest + num) = *((char*)src + num); }
return dest; } //src stay dest Behind else { void* ret = dest; while (num--) {
*(char*)dest = *(char*)src; dest = (char*)dest + 1; src = (char*)src + 1; }
return ret; } }
13.memcmp

int memcmp(const void* ptr1, const void* ptr2, size_t num);

 1. Compare from ptr1 Pointer and ptr2 Pointer start num Bytes of data , and strcmp A little similar , The return value is also divided into <0,==0 and >0 Three kinds .

use :

Simulation Implementation :
int my_memcmp(const void* ptr1, const void* ptr2, size_t num) { num -= 1;
while (num-- && (*(char*)ptr1 == *(char*)ptr2)) { ptr1 = (char*)ptr1 + 1; ptr2
= (char*)ptr2 + 1; } if ((*(char*)ptr1 == *(char*)ptr2)) { return 0; } else if
(*(char*)ptr1 > *(char*)ptr2) { return 1; } else { return -1; } }
Because the pointer +num-1 It's time to compare the location of the last byte size space , So at first num be going to -1.

2. Introduction to character functions

  Function returns true if its parameters meet the following conditions ( wrong 0 Indicate true )
iscntrl Any control character
isspace White space character : Space ‘ ’, Page change ‘\f’, Line feed '\n', enter ‘\r’, Box drawings '\t' Or vertical tab '\v'
isdigit Decimal digit 0~9
isxdigit Hexadecimal digit , 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 symbol
isprint Any printable character , Including graphic characters and white space characters
use :

be careful : Parameters will be converted to ASCII code
int main() { printf("%d\n", iscntrl(1)); printf("%d\n", isspace(3));
printf("%d\n", isdigit(48)); printf("%d\n", isxdigit(49)); printf("%d\n",
islower('A')); printf("%d\n", isupper('A')); printf("%d\n", isalpha('a'));
printf("%d\n", isalnum('a')); printf("%d\n", ispunct('.')); printf("%d\n",
isgraph('#')); printf("%d\n", isprint('3')); return 0; }
Character conversion :

int toupper(int c);

int tolower(int c);

use :
int main() { putchar(toupper('c')); printf("\n"); putchar(tolower('C'));
return 0; }

That's all about string functions and character functions , It will also be updated irregularly in the future

Technology
©2019-2020 Toolsou All rights reserved,
Solve in servlet The Chinese output in is a question mark C String function and character function in language MySQL management 35 A small coup optimization Java performance —— Concise article Seven sorting algorithms (java code ) use Ansible Batch deployment SSH Password free login to remote host according to excel generate create Build table SQL sentence Spring Source code series ( sixteen )Spring merge BeanDefinition Principle of Virtual machine installation Linux course What are the common exception classes ?