[C language advanced] character function and string function

Preface
Before the article, we must know that the C language handles characters and strings frequently, but the C language itself does not have a string type, and strings are usually placed in constant strings or character arrays. String constants are suitable for those string functions that do not modify it.

Introduce commonly used string functions

1.strlen(string length)
2.strcpy
3.strcat
4.strcmp
5.strncpy
6.strncat
7.strncmp
8.strstr(string search)
9.strtok
10.strerror(error information report)
memory operation function
11. memcpy
12.memmove
13.memset
14.memcmp

strlen

my_strlen (const char * str ); The
string has'\0' as the end sign, and the strlen function returns the number of characters that appear before the'\0' in the string (not including'\0')
strlen and sizeof are different Is'\0' The
next thing we have to do is to implement the function (here to remember the difference between sizeof and strlen mentioned in the previous article)

int my_strlen(const char * str) 
{
    
      int count = 0;  
   while(*str) 
    {
    
    
      count++;   str++;  
     }  
 return count; } 

strcpy

Introduction: cpy means copy, which means copy source into destination
1. The source string must end with'\0'.
2. Copy the'\0' in the source string to the target space.
3. The target space must be large enough to ensure that the source string can be stored.
4. The target space must be variable. Learn to simulate the implementation of
functions

char *my_strcpy(char *dest, const char*src)
 {
    
       char *ret = dest;  assert(dest != NULL);
     assert(src != NULL);    
     while((*dest++ = *src++))  
     {
    
       
         ;  
     }  
     return ret; } 

strcat

Note: 1. The source string must end with'\0'.
2. The target space must be large enough to hold the content of the source string.
3. The target space must be modifiable and
simulated

char *my_strcat(char *dest, const char*src) {
    
      
    char *ret = dest;  
     assert(dest != NULL);  
     assert(src != NULL);  
      while(*dest) 
      {
    
       
       dest++;  
      } 
      while((*dest++ = *src++)) 
      {
    
       
          ; 
       }   
    return ret;
 }

Here I want to mention why there is such a statement for assert. In fact, it means to judge whether the pointer is empty before. If we pass in the parameter to refer to a null pointer, we don't have to proceed further.

strcmp

Provisions:
1. The first string is greater than the second string, then a number greater than 0 is returned
2. The first string is equal to the second string, then 0 is returned
3. The first string is less than the second string, number less than 0 is returned
analog implementation

int my_strcmp (const char * src, const char * dst) 
{
    
             
    int ret = 0 ;   
    assert(src != NULL);      
    assert(dest != NULL);         
    while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)                          
         ++src, ++dst; 
  
        if ( ret < 0 )                
         ret = -1 ;         
         else if ( ret > 0 )                 
         ret = 1 ; 
         return( ret ); } 

Length-limited function

strncpy
strncat
strncmp
These three functions are almost the same as before. Can you find any difference?
There is always an N, why add an N. This is the limitation on the length. For
example:
char * strcat (char * destination, const char * source );

char * strncat (char * destination, const char * source, size_t num)
has one more limitation on size, so when simulating functions, you need to add a limitation on length.
Insert picture description here

strstr

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

strstr is equivalent to children going to their parents to
see if the input string is a substring of the previous string.
For example, a set A (1, 3, 4, 5)
if B (1, 4) go in to find then B is A subset of
analog functions

char *my_strstr(const char* str1, const char* str2 ) 
{
    
      
    assert(str1);  
    assert(str2);    
    char *cp = (char*)str1;  
    char *substr = (char *)str2;  
    char *s1 = NULL;    
    if(*str2 == '\0')   return NULL;     
           while(*cp) 
           {
    
       
              s1 = cp;   
              substr = str2;   
              while(*s1 && *substr && (*s1 == *substr))   
              {
    
       
               s1++;    
               substr++; 
              }
              if(*substr == '\0')    
               return cp;   
                cp++; 
         }
 }

Use code

#include <stdio.h> 
#include <string.h>
int main() 
{
    
    
	char str[] = "This is a simple string";
	char * pch;
	pch = strstr(str, "simple");
	strncpy(pch, "sample", 6);
	puts(str);
	return 0;
}

Insert picture description here

strtok

char * strtok (char * str, const char * sep );
1. The sep parameter is a string, which defines the set of characters used as a separator
2. The first parameter specifies a string, which contains 0 or more Marks separated by one or more separators in the sep string.
3. The strtok function finds the next mark in str, ends it with \0, and returns a pointer to this mark. (Note: The strtok function will change the string being manipulated, so the string split by the strtok function is generally a temporary copy and can be modified.)
4. The first parameter of the strtok function is not NULL, the function will Find the first mark in str, strtok function will save its position in the string.
5. The first parameter of the strtok function is NULL, the function will start at the saved position in the same string and search for the next token.
6. If there are no more tags in the string, a NULL pointer is returned.
Use code

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h> #include <string.h>
int main()
{
    
    
	char str[] = "- This, a sample string.";
	char * pch; 
	printf("Splitting string \"%s\" into tokens:\n", str);
	pch = strtok(str, " ,.-");
	while (pch != NULL)  
	{
    
    
		printf("%s\n", pch);
		pch = strtok(NULL, " ,.-");
	}
	return 0;
}

operation result
Insert picture description here

strerror

The error message corresponding to the returned error code must include its header file

#include <stdio.h> 
#include <string.h>
#include <errno.h>
//必须包含的头文件

Introduction to character classification functions
Insert picture description here

memcpy

Rules:
1. The function memcpy copies num bytes of data from the position of the source to the memory position of the destination. 2. This function will not stop when it encounters'\0'.
3. If there is any overlap between source and destination, the result of the copy is undefined.
The difference between this function and strcpy is that one is a string copy and the other is a memory copy. The rest are the same, and the length can be limited.

memmove

Rule
1. The difference with memcpy is that the source memory block and target memory block processed by the memmove function can overlap. If the source 2. space and the target space overlap, you have to use the memmove function to process the
simulation

void* my_memmove(void* dst, const void* src, int size)
{
    
    
	assert(src);
	assert(dst);

	char* str_dst = (char*)dst;
	const char* str_src = (const char*)src;
	// 1、后重叠,或者是不重叠右边的拷贝,倒着拷贝
	// 2、前重叠,或者是不重叠左边的拷贝,正着拷贝
	if(str_src < str_dst)
	{
    
    
		for (int end = size - 1; end >= 0; --end)
		{
    
    
			//*(str_dst+end) = *(str_src + end);
			str_dst[end] = str_src[end];
		}
	}
	else
	{
    
    
		for (int start = 0; start < size; ++start)
		{
    
    
			str_dst[start] = str_src[start];
		}
	}

	return dst;
}

memcmp

Definition: int memcmp (const void * ptr1, const void * ptr2, size_t num );
Rule: Compare num bytes starting from the pointers of ptr1 and ptr2. The return value is as follows: The Insert picture description here
difference from strcmp is that memcmp will compare the back of'\0' While strcmp will not

Guess you like

Origin blog.csdn.net/weixin_43762735/article/details/109330311