当前位置:网站首页>[advanced level 11 of C language -- character and string functions and their simulation implementation (2)]

[advanced level 11 of C language -- character and string functions and their simulation implementation (2)]

2022-04-23 18:53:00 Beginners of C language


Preface

This article goes on to learn about character and string functions , And simulated with code . The main learning contents include :

4、 String search

  • strstr
  • strtok

5、 Error message report

  • strerror

6、 Character manipulation functions

7、 Memory manipulation function

  • memcpy
  • memmove
  • memset
  • memcmp

4、 String search

4.1 Library function strstr

char * strstr ( const char *str1, const char * str2);
  • Return to point str1 The first one to appear str2 The pointer to , If str2 No str1 Part of , Return null pointer
int main()
{
    
	char a1[] = "abbbcdef";
	char a2[] = "bbc";
	char* ret = strstr(a1, a2);

	if (NULL==ret)
	{
    
		printf(" Could not find substring \n");
	}
	else
	{
    
		printf("%s\n", ret);
	}
}

4.2 Simulate the implementation of library functions strstr

char* my_strstr(const char* p1, const char* p2)
{
    
	assert(p1&&p2);
	const char* s1 = p1;// Give the pointer the initial position 
	const char* s2 = p2;// Give the pointer the initial position 
	const char* cur = p1;// Record the current pointer position of the string 

	while (*cur)
	{
    
		s1 = cur;
		s2 = p2;// Move to the initial position 
		while (*s1 && *s2 && (*s1==*s2))
		{
    
			s1++;// When equal , Pointer backward , Until two are not equal or one is 0
			s2++;
		}
		if (*s2=='\0')
		{
    
			return (char*)cur;
		}
		cur++;// It's not equal , Current pointer plus 1
	}
	// Jump out of , It's just a string 1 Move to the end 
	return NULL;
}
int main()
{
    
	char a1[] = "abbbcdef";
	char a2[] = "bbc";
	char* ret = my_strstr(a1, a2);
	if (NULL==ret)
	{
    
		printf(" Could not find substring \n");
	}
	else
	{
    
		printf("%s\n", ret);
	}
}

The results are as follows :

 Insert picture description here

4.3 Library function strtok

char * strtok ( char * str, const char * sep );
  • sep The parameter is a string , Defines the set of characters used as delimiters. 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
  • 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
int main()
{
    
	char a[] = "[email protected]@hello world";
	char a2[50] = {
     0 };
	strcpy(a2, a);
	printf("%s\n", a2);

	const char* sep = "@. ";// Three separators 
	printf("%s\n", strtok(a2, sep));//learnC
	printf("%s\n", strtok(NULL, sep));//day
	printf("%s\n", strtok(NULL, sep));//day
	return 0;
}

The results are as follows :
 Insert picture description here

 Insert picture description here

int main()
{
    
	char a[] = "[email protected]@hello world";
	char a2[50] = {
     0 };
	strcpy(a2, a);
	printf("%s\n", a2);

	const char* sep = "@. ";// Three separators 
	char* str = NULL;
	// Find multiple strings separated by circular separators , Not empty , Just find the next one , Until the end 
	for (str =strtok(a2,sep); str != NULL; str=strtok(NULL,sep))
	{
    
		printf("%s\n", str);
	}
	return 0;

}

The results are as follows :

 Insert picture description here

5、 Error message report

5.1 Library function strerror

char * strerror ( int errnum );
  • Return error code , The corresponding error message
int main()
{
    
	int* p = (int*)malloc(INT_MAX);// Apply for memory in heap 
	if (p==NULL)
	{
    
		printf("%s\n", strerror(errno));// Print error message 
		return 1;
	}
	return 0;
}

The results are as follows :

 Insert picture description here

6、 Character manipulation functions

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

7、 Memory manipulation function

7.1 Library function memcpy

void * memcpy ( void * destination, const void * source, size_t num );
  • 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
int main()
{
    
	int a1[10] = {
     1,2,3,4,5,6,7,8,9,10 };
	int a2[5] = {
     0 };
	memcpy(a2, a1, 20);
	int sz = sizeof(a1) / sizeof(a1[0]);
	for (int i = 0; i < sz; i++)
	{
    
		printf("%d\n", a2[i]);
	}
	return 0;
}

7.2 Simulate the implementation of library functions memcpy

// Simulation Implementation 
void* my_memcpy(void* dest, const void* src, size_t cnt)
{
    
	assert(dest&&src);
	void* ret = dest;// Receive any type of data 
	while (cnt--)
	{
    
		*(char*)dest = *(char*)src;// Swap in byte order 
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}
	return ret;
}

int main()
{
    
	int a1[10] = {
     1,2,3,4,5,6,7,8,9,10 };
	int a2[5] = {
     0 };
	
	my_memcpy(a2, a1, 20);
	int sz = sizeof(a1) / sizeof(a1[0]);
	for (int i = 0; i < sz; i++)
	{
    
		printf("%d\n", a2[i]);
	}
	return 0;
}

The results are as follows :

 Insert picture description here
 Insert picture description here

7.3 Library function memmove

void * memmove ( void * destination, const void * source, size_t num );
  • 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
int main()
{
    
	int a1[10] = {
     1,2,3,4,5,6,7,8,9,10 };	
	memmove(a1+2, a1, 20);	
	int sz = sizeof(a1) / sizeof(a1[0]);
	for (int i = 0; i < sz; i++)
	{
    
		printf("%d\n", a1[i]);
	}
	return 0;
}

7.4 Simulate the implementation of library functions memmove

// Simulation Implementation 
void* my_memmove(void* dest, const void* src, size_t cnt)
{
    
	assert(dest&&src);
	void* ret = dest;
	if (dest<src)
	{
    // Copy from left to right 
		while (cnt--)
		{
    
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
    // From right to left 
		while (cnt--)
		{
    
			*((char*)dest + cnt) = *((char*)src + cnt);
		}
	}
	return ret;
}

int main()
{
    
	int a1[10] = {
     1,2,3,4,5,6,7,8,9,10 };
	my_memmove(a1+2, a1, 20);
	int sz = sizeof(a1) / sizeof(a1[0]);
	for (int i = 0; i < sz; i++)
	{
    
		printf("%d\n", a1[i]);
	}
	return 0;
}

The results are as follows :

 Insert picture description here

7.5 Library function memcmp

int memcmp ( const void * ptr1, const void * ptr2, size_t num );
  • Compare from ptr1 and ptr2 The pointer starts with num Bytes
  • Return value less than 0, The data of the preceding byte is smaller than the data of the following corresponding byte
  • The return value is equal to 0, The data of the preceding byte is equal to the data of the following corresponding byte
  • Return value greater than 0, The data of the preceding byte is larger than the data of the following corresponding byte
int main()
{
    
	int a1[] = {
     1,2,3,4,5 };
	int a2[] = {
     1,2,3,4,0x11223305 };
	int ret = memcmp(a1, a2, 18);
	printf("%d\n", ret);
	return 0;
}

The results are as follows :

 Insert picture description here

7.6 Library function memset

void *memset( void *dest, int c, size_t count );
  • memset Function will Target space dest Of in total count The contents of bytes are set to characters c.
int main()
{
    
	int a[] = {
     0x11111111,0x22222222,3,4,5 };
	memset(a, 6, 20);
	return 0;
}

The results are as follows :

 Insert picture description here


summary

The learning of string library function is basically over . It's a little confusing after learning , This content can be used as a dictionary , Check again when necessary .

It feels a little boring to learn string library functions alone , You can understand and master the usage of these functions only after you brush the questions later .

Library functions to achieve learning dazzling , There's one more thing I haven't written completely , Add content later .

The next article updates the content related to structure .

版权声明
本文为[Beginners of C language]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231851188685.html