Character function and string function

This blog introduces some functions and how to simulate their implementation

strlen function

Introduction: calculate the length of the string str until the null end character, but excluding the null end character
Prototype: size_t strlen(const char *str)
Return value: returns the length of the string

Note:
1. The string ends with '\ 0'. strlen function returns the number of characters appearing before '\ 0' in the string (excluding '\ 0').
2. The string pointed to by the parameter must end with '\ 0'. Note that the return value of the function is size_t is unsigned.

Simulate the implementation of strlen function

Common recursive and pointer pointer methods

1. Recursion

#include<stdio.h>
//Recursive implementation / / recursion is nothing more than two-step initial conditions and approximation conditions
int my_strlen(char *str)
{
    if(*str=='\0')                         //Returns 0 if the array is' \ 0 '
    	return 0; 
    else
       return 1+my_strlen(str+1);          //Not '\ 0 1 + pointer + 1 points to the next element              
}
int main()
{
    char arr[]="bite";
    printf("%d",my_strlen(arr));

	return 0;
}


2. Pointer pointer

Pointer pointer = number of elements in the middle of pointer

#include<stdio.h>

int my_strlen(char *str)
{
   char*begin=str;       //Record the initial position of the pointer
   while(*str!='\0')
   		str++;          //Loop record str to position before '\ 0'
   return str - begin;
}

int main()
{
    char arr[]="bite";
    printf("%d",my_strlen(arr));

	return 0;
}

strcpy function VS stcnpy function


Char * strcpy (char * DeST (receiving copied string), const char * src (copied string)) copies the string pointed by src to dest.

Simulate the implementation of strcpy function

#include<stdio.h>
int main()
{
    char arr1[]="bite";
    char arr2[10]={0}
    
    char *dest=arr1;             //Assign the first element of arr1 to the dest pointer
    char *sec=arr2;              //Assign the first element of arr2 to the sec pointer
    while(*sec++=*dest++)        // *Priority over++
    {                            //Assign 'b' to sec first
             ;                   //When it reaches' \ 0 ', it will be assigned to sec first and then judged, because when (' \ 0 ') is false, it will not be judged later
    }
    printf("%s",arr2);

	return 0;
}




Char * strncpy (char * destination, const char * source, size_t Num) the difference is that strncpy can specify how many characters need to be copied

How to understand the second sentence
example

#pragma warning(disable : 4996)
#include<stdio.h>
#include<string.h>
int main()
{
	char a[20] = "bite666666";
	char b[] ="peng";

	strncpy(a,b,6); //Copy the six characters in b to a. you can know that only five elements in b are less than num, so 0 will be added
	return 0;
}


You can see that the sixth element a[5] is assigned as' \ 0 '

strcat VS strncat


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

Connect the score to the destination and add '\ 0' at the end of the score


be careful:

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

Connect the num characters in the score after the destination and fill in '\ 0' at the end of the score


Simulate the implementation of strcat function

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


strcmp VS strncmp


The strcmp function compares two strings


Function prototype: int StrCmp (const char * STR1, const char * STR2)


Function prototype: int strncmp (const char * STR1, const char * STR2, size_t Num);

Compare the first n characters of the string
STR1 and STR2 are the two strings to be compared, and num is the number of characters to be compared



Simulated implementation of strcmp

Principle: the comparison of string size is determined by the order on the ASCII code table, which is also the value of characters

int my_strcmp(const char *str1,const char *str2)
{
   while(str1 == str2)                //If two characters are the same, + + backward ratio
   {	
   		if(str1=='\0' &&str2 =='\0')
   			return 0;
   			
     	str1++;
     	str2++;
   }
   return *str1 -*str2;  //The returned value is ASCII code. If * STR1 - * STR2 > 0, it means STR1 > STR2. On the contrary, STR1 < STR2



strstr function

Function: retrieves the position of the substring in the string for the first time

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

Check whether str2 appears in str1

Returns the address where the substring str2 first appears in the string str1; If no substring is retrieved, NULL is returned

#include<stdio.h>
#include<string.h>
int main()
{
    char *str1 = "bite is good";
    char *str2 = "is";
    char *s = strstr(str1, str2);
    printf("%s\n", s);
    return 0;
}



Simulation implementation str

char* my_strstr(const char* str1, const char* str2)
{
	assert(str1 && str2);
	char* s1 = NULL;           
	char* s2 = NULL;            
	
	char* cp = (char*)str1;    //Assign str1 to cp and let cp traverse and remember the location
	while (*cp)                //cp traversal str1
	{
		s1 = cp;               //s1 to receive the characters to be compared each time
	    s2 = (char*)str2;     //s2 receives the content to be compared with s1
		
        while (*s1 == *s2 && *s1 && *s2)    //Find the same and not equal to slash 0
		{
			s1++;                         //Both s1 and s2 are + + backward to compare the next one
			s2++;
			if (*s2 == '\0')       //When s2 is \ 0, it indicates that the comparison is completed and the address of the comparison is returned
				return cp;
		}
		
		cp++;                    //When s1 and s2 are not equal, cp + + points back to the next character for comparison
	}
	return NULL;
}


/*example str1="saatg" str2="at"   The result is atg

1. cp='s'  s1='s' s2='a' while (*s1 == *s2 && *s1 && *s2)Not established

2. cp++  cp='a' s1='a' s2='a'  while (*s1 == *s2 && *s1 && *s2)establish
   s1++  s2++   s1='a' s2='t'  if (*s2 == '\0')Not established 

3. Continue the cycle while (*s1 == *s2 && *s1 && *s2) s1 ='a' != s2='t' Not established cp++

4. cp='a' s1='a' s2='a'  while (*s1 == *s2 && *s1 && *s2)establish 
   s1++   s2++  s1='t'   s2='t'  if (*s2 == '\0')establish
   
5.continue while s1=t s2=t Equal establishment s1++ s2++ s1='g' s2='\0'  if (*s2 == '\0')Not established
6.return cp   here cp Return to the second'a'Address of 


strerror

Function: returns the description string of the error reason

char * strerror ( int errnum )

strerror() is used to query the description string of the error reason according to the error code of the parameter errnum, and then return the string pointer

Personally, I don't think it's easier to use than perror function

int main()
{
	FILE*pf=fopen("test1","r");
	if(pf =	NULL)
	{
		perror("fopen");
		return 1;
	}
	return 0;
}

perror( ) //Fill in the words to be output in parentheses


Common character classification function

Keywords: C C++ data structure

Added by nuxy on Fri, 04 Feb 2022 16:12:21 +0200