❤️ Detailed explanation of library function ❤️ Take a look at these C language essential library functions. Can you understand them all

⭐ ♪ previous words ⭐ ️

This blog is about the introduction of C language library function pointers ❤️ Detailed explanation of library function ❤️, Take a look at these C language essential library functions. Can you find them according to the directory.

👋 Hi~ o( ̄▽  ̄) here is the pig programmer
👀 Nice to meet you O(∩) O!
🌱 Now sprouting
💞 The level of bloggers is limited. If you find an error, you must inform the author in time! Thank you, thank you!
📫 Blogger's code cloud gitee Usually, the program code written by bloggers is in it.

📌 Find string length

⭐️⭐️1. strlen

🌿 Syntax:

size_t strlen ( const char * str )

🌿 Usage: strlen is the work of a counter. It starts scanning from a certain position in memory (which can be the beginning of a string, a certain position in the middle, or even an uncertain memory area) until it encounters the first string terminator '\ 0', and then returns the counter value.

🌿 matters needing attention:

strlen calculates the length of the string str (unsigned int type), excluding '\ 0'

🌿 give an example:

##include <stdio.h>
#include <string.h>
 
int main(void){
 
    char str [50] = "HelloWorld'\0'Hi";//Define character array str capacity: 50
    int len = strlen(str);//Define the integer type int len, and then assign the length calculated by strlen(str) to len
    printf("len Length of:%d\n",len);
    return 0;
}

🌿 Output results:

len Length of: 11//Calculation length "HelloWorld" + '11 in total, excluding \ 0'

🌿 Implement your own mystrlen

int mystrlen(char c[])
{
	int i = 0;
	while (c[i])		//c[i]!=NULL
	{
		i++;
	}
	return i;
}

📌 String function with unlimited length

⭐️⭐️2. strcpy

🌿 Syntax:

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

🌿 Usage: copy the string pointed to by source to destination

🌿 matters needing attention:

  1. The source string must end with '\ 0'.
  2. The '\ 0' in the source string will be copied to the destination space.
  3. The destination space must be large enough to hold the source string.
  4. The target space must be variable.

🌿 give an example:

/* strcpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}

🌿 Output results:

str1: Sample string
str2: Sample string
str3: copy successful

🌿 Implement your own mystrcpy

void mystrcpy(char to[], char from[])
{
	int i = 0;
	while (from[i])			//from[i]!=NULL
	{
		to[i] = from[i];
		i++;
	}
	to[i] = 0;		//Add a terminator after the last character of the array to []
}

⭐️⭐️3. strcat

🌿 Syntax:

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

🌿 Usage: append a string source to the end of another string destination to form a new string

🌿 matters needing attention:

  1. The source string source must end with '\ 0'.
  2. The destination space must be large enough to accommodate the contents of the source string.
  3. destination space must be modifiable.

🌿 give an example:

int main()
{
	char dest[30] = { "hello" };
	char src[] = {"world"};
	strcat(dest, src);
	printf("%s", dest);
	return 0;
}

Output results:

helloworld

🌿 Implement your own mystrcat

char* my_strcat(char* dest, const char* src)
{
	char* ret = dest;
	while (*dest)//Found '\ 0' at the end of the objective function
	{
		dest++;
	}
	while (*dest++ = *src++)//Append to source string
	{
		;
	}
	return ret;
}
int main()
{
	char a1[30] = { "abc" };
	char a2[] = { "def" };
	my_strcat(a1, a2);
	printf("%s", a1);
	return 0;
}

⭐️⭐️4. strcmp

🌿 Syntax:

int strcmp ( const char * str1, const char * str2 )//be careful!!! The content of the string is compared here, not the length

🌿 Usage: compare the size of two strings

What's the use of this library function?
🌿🌿 Usage scenario: it can be used when we want to compare whether the entered passwords are equal~

🌿 Standard provisions:

Compare from the first character. If the same, compare the next character:

  1. If the first string is greater than the second string, a number greater than 0 is returned
  2. Returns 0 if the first string is equal to the second string
  3. If the first string is less than the second string, a number less than 0 is returned

🌿 give an example:

#include <stdio.h>
#include <string.h>	

int main(void)
{
	char *a = "English";
    char *b = "ENGLISH";
    char *c = "english";
	//strcmp() can only compare strings, and other forms of parameters cannot be compared 
	printf("strcmp(a, b):%d\n", strcmp(a, b));//Comparison between strings 
    printf("strcmp(a, c):%d\n", strcmp(a, c));

	return 0;
}

🌿🌿 Output results:

strcmp(a, b):1
strcmp(a, c):-1

🌿 Implement your own mystrcmp

int  mystrcmp(const char* str1, const char* str2)
{
	while ( *str1 == *str2)
	{
		if (*str1 == '\0')
			return 0;
		str1++; str2++;
	}
	return *str1 - *str2;
}
int main()
{
	char str1[] = { "hello" };
	char str2[] = { "world" };
	int t = mystrcmp(str1 , str2);
	printf("%d", t);
	return 0;
}

📌 Introduction to string functions with limited length

🍂🍂🍂 I believe you can find that the function with restricted string has one more variable num compared with the function without restriction. In this way, the function is relatively safe because there is a number limit

⭐️⭐️5. strncpy

🌿 Syntax:

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

🌿 Usage: copy the string starting from the source address and containing the NULL terminator to the address space starting from destination

🌿 matters needing attention:

Copy num characters from the source string to the destination space.
If the length of the source string is less than num, after copying the source string, append 0 to num after the destination.

🌿 give an example:

/* strncpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]= "To be or not to be";
  char str2[40];
  char str3[40];

  strncpy ( str2, str1, sizeof(str2) );

  strncpy ( str3, str2, 5 );
  str3[5] = '\0';   /* null character manually added */

  puts (str1);
  puts (str2);
  puts (str3);

  return 0;
}

🌿🌿 Output results:

To be or not to be
To be or not to be
To be

🌿 Implement your own mystrncpy

char*  mystrncpy(char *dest, const char *src, size_t count)
{
    char *tmp = dest;
    while (count) {
        if ((*tmp = *src) != 0)
            src++;
        tmp++;
        count--;
    }
    return dest;
}

⭐️⭐️6. strncat

🌿 Syntax:

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

🌿 Use: append a string to the end of another string

🌿 matters needing attention:

If num is greater than the number of strings that can be appended, append to '\ 0' will end

🌿 give an example:

/* strncat example */
#include <stdio.h>
#include <string.h>
int main ()
{
 char str1[20];
 char str2[20];
 strcpy (str1,"To be ");
 strcpy (str2,"or not to be");
 strncat (str1, str2, 6);
 puts (str1);
 return 0;
}

🌿🌿 Output results:

To be or not to be

🌿 Implement your own mystrncat

char *mystrncat(char *dest, const char *src, int n)
{
	char *ret = dest;
	while (*dest != '\0')
	{
		dest++;
	}
	while (n && (*dest++ = *src++) != '\0')
	{
		n--;
	}
	dest = '\0';
	return ret;
}

⭐️⭐️7. strncmp

🌿 Syntax:

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

🌿 Usage: compare the size of two strings

🌿 matters needing attention:

🌿🌿 The comparison shows that another character is different, or a string ends, or num characters are all compared.

Compare from the first character. If the same, compare the next character:

  1. If the first string is greater than the second string, a number greater than 0 is returned
  2. Returns 0 if the first string is equal to the second string
  3. If the first string is less than the second string, a number less than 0 is returned

🌿 give an example:

/* strncmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
  int n;
  puts ("Looking for R2 astromech droids...");
  for (n=0 ; n<3 ; n++)
    if (strncmp (str[n],"R2xx",2) == 0)
    {
      printf ("found %s\n",str[n]);
    }
  return 0;
}

🌿🌿 Output results:

Looking for R2 astromech droids...
found R2D2
found R2A6

🌿 Implement your own mystrncmp

int  mystrncmp(const char* str1, const char* str2,int num)
{
	char* ret = str1;
	while ( *str1 == *str2 && num>0)
		{
		if (*str2 == '\0')
			*ret = '\0';
			str1++; str2++; num--;
		}

	
		return ret;
}

📌 String lookup

⭐️⭐️8. strstr

🌿 Syntax:

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

🌿 Usage: the strstr(str1,str2) function is used to determine whether the string str2 is a substring of str1. If yes, the function returns the address where str2 first appears in str1; Otherwise, NULL is returned.

🌿 matters needing attention:

🌿🌿 The comparison shows that another character is different, or a string ends, or num characters are all compared.

Compare from the first character. If the same, compare the next character:

1. If the first string is greater than the second string, a number greater than 0 will be returned
2. If the first string is equal to the second string, 0 is returned
3. If the first string is less than the second string, a number less than 0 will be returned

🌿 give an example:

/* strstr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="This is a simple string";
  char * pch;
  pch = strstr (str,"simple");
  if (pch != NULL)
    strncpy (pch,"sample",6);
  puts (str);
  return 0;
}

🌿🌿 Output results:

This is a sample string

🌿 Implement your own mystr

char*  mystrstr(const char* str1, const char* str2)
{
	char* s1;
	char* s2;
	char* cp = str1;
	if ( *str2 == '\0')
		return str1;
	while (*cp)
	{
		s1 = cp;
		s2 = str2;
		while (*s1 != '\0' && *s2!= '\0' && * s1 == *s2)
		{
			s1++; s2++;
		}
		if (*s2 == '\0')
		{
			return cp;
		}
		cp++;
	}
	return NULL;
}
int main()
{
	char str1[] = { "helloworld" };
	char str2[] = { "world" };
	char* t = mystrstr(str1 , str2);
	printf("%s", t);
	return 0;
}

⭐️⭐️9. strtok

🌿 Syntax:

char * strtok ( char * str, const char * delimiters )

🌿 Use:

Acting on the string str, taking the characters in delimiters as the delimiter to cut str into a substring; If str is NULL, the pointer saved by the function is SAVE_PTR will be used as the starting position in the next call.

Return value: the first substring to which the delimiter matches

🌿 matters needing attention:

1. The function is used to decompose a string. The so-called decomposition means that no new string is generated, but the delimiter is modified to '/ 0' at the position where the delimiter first appears in the content pointed to by s, so strtok is used to return the first substring for the first time

2. After the first substring extraction, continue to extract the source string str, and set the first parameter of strtok to NULL in subsequent calls (the second, third... Nth) (indicates that the function continues to decompose the string from the implicitly saved position of the previous call; for the previous call, a this pointer points to the next bit of the delimiter before the end of the first call)

3. When the this pointer points to "\ 0", that is, there is no split substring, and NULL is returned

4. Delimiters can be understood as a set of delimiters, and all characters in delimiters can be used as delimiters.

5. When strtok is called, if the starting position is the separator, the separator from the starting position is ignored

6. 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.)

🌿 give an example:

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");//Just fill in NULL here, because the function will remember the next starting position of the character that has been searched before
  }
  return 0;
}

🌿🌿 Output results:

This
a
sample
string

📌 Error message report

⭐️⭐️10.strerror

🌿 Syntax:

char * strerror ( int errnum )

🌿 Use:

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

🌿 matters needing attention:

Include #include < errno. H > in the program code, and then each time the program call fails, the system will automatically fill the global variable errno with the error code. You only need to read the global variable errno to get the failure reason.

🌿🌿 Each error code has a corresponding error message:

🌿🌿🌿 Print the error codes of 0, 1, 2 and 3 as follows:

int main()
{
	printf("%s\n", strerror(0));
	printf("%s\n", strerror(1));
	printf("%s\n", strerror(2));
	printf("%s\n", strerror(3));
	return 0;
}

🌿🌿🌿 The results are as follows:

No error
Operation not permitted
No such file or directory
No such process

🌿 give an example:

/* strerror example : error list */
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main ()
{
  FILE * pFile;
  pFile = fopen ("unexist.ent","r");
  if (pFile == NULL)
    printf ("%s\n",strerror(errno));
  return 0;
}

🌿🌿 Output results:

No such file or directory

📌 Memory operation function

⭐️⭐️11. memcpy

🌿 Syntax:

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

🌿 Use:

Taking the address pointed to by source as the starting point, copy the continuous num bytes of data to the memory starting from the address pointed to by destination. The function has three parameters. The first is the destination address, the second is the source address, and the third is the data length

Return value: the first substring to which the delimiter matches

🌿 matters needing attention:

1. The function memcpy copies num bytes of data back from the source location to the destination memory location.
2. This function will not stop when it encounters' \ 0 '.
3. If there is any overlap between source and destination, the copied result will be wrong. At this time, another library function memmove will be used.

🌿 give an example:

int main()
{
	int a[10] = { 1,2,3,4,5,6,7,8,9 };
	int b[20] = { 0 };
	memcpy(b, a, 40);        //Here 40 is equivalent to 10*sizeof(int)
	for (int i = 0; i < 20; i++)
	{
		printf("%d ", b[i]);
	}
	return 0;
}

🌿🌿 Output results:

1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0

🌿 Implement your own memcpy

void* mymemcpy(void* dest, const void* src, size_t count)
{
	void* ret = dest;
	while (count--)
	{
		*(char*)dest = *(char*)src;
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}
	return ret;
}
int main()
{
	int a[10] = { 1,2,3,4,5,6,7,8,9 };
	int b[20] = { 0 };
	mymemcpy(b, a, 40);
	for (int i = 0; i < 20; i++)
	{
		printf("%d ", b[i]);
	}
	return 0;
}

⭐️⭐️12. memmove

🌿 Syntax:

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

🌿 Use:

When using memcpy, errors may occur when there is memory overlap (for example, copying the last section of its own string to the first section). memmove solves this problem by copying from the back to the front when memory overlap occurs

🌿 matters needing attention:

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

🌿 give an example:

/* memmove example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "memmove can be very useful......";
  memmove (str+20,str+15,11);
  puts (str);
  return 0;
}

🌿🌿 Output results:

memmove can be very very useful.

🌿 Implement your own memmove

void* mymemmove(void* dest, const void* src, size_t count)
{
	void* ret = dest;
	if (dest < src)
	{
		while (count--)
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		while (count--)
		{
			*((char*)dest + count) = *((char*)src + count);
		}
	}
	
	return ret;
}
int main()
{
	int a[10] = { 1,2,3,4,5,6,7,8,9 };
	mymemmove(a+2, a, 16);
	for (int i = 0; i < 20; i++)
	{
		printf("%d ", a[i]);
	}
	return 0;
}

⭐️⭐️13. memset

🌿 Syntax:

void *memset(void *s, int ch, size_t n);

🌿 Use:

Set all the contents of a block of memory to the specified value. This function usually initializes the newly applied memory.

🌿 matters needing attention:

  1. The memset() function is commonly used for memory space initialization.

  2. The profound connotation of memset(): it is used to set all a memory space to a certain character. It is generally used to initialize the defined string

for example:memset(a,'\0',sizeof(a));
  1. memset can easily empty variables or arrays of a structure type.

🌿 give an example:

/* memset example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "almost every programmer should know memset!";
  memset (str,'-',6);
  puts (str);
  return 0;
}

🌿🌿 Output results:

------ every programmer should know memset!

⭐️⭐️14. memcmp

🌿 Syntax:

int memcmp(const void *buf1, const void *buf2, unsigned int count);

🌿 Use:

  1. When buf1 < buf2, the return value is < 0

  2. When buf1=buf2, the return value = 0

  3. When buf1 > buf2, the return value is > 0

🌿 matters needing attention:

  1. This function compares by byte.

🌿🌿🌿 For example:

When s1 and S2 are strings, memcmp(s1,s2,1) is to compare the ascII code value of the first byte of s1 and S2;

memcmp(s1,s2,n) is to compare the ascII code values of the first n bytes of s1 and s2;

char *s1="abc";

char *s2="acd";

int r=memcmp(s1,s2,3);

The first three bytes of s1 and s2 are compared. The first byte is equal. The size of the second byte has been determined in the comparison. There is no need to compare the third byte, so r=-1

  1. For memcmp(), if the two strings are the same and the count is greater than the string length, memcmp will not stop at \ 0 and will continue to compare the memory units after \ 0
  2. If you want to compare strings using memcmp, make sure that the count cannot exceed the length of the shortest string, otherwise the result may be wrong.

🌿 give an example:

/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n=memcmp ( buffer1, buffer2, sizeof(buffer1) );

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  re

🌿🌿 Output results:

'DWgaOtP12df0' is greater than 'DWGAOTP12DF0'.

Keywords: C

Added by toms100 on Tue, 21 Sep 2021 11:44:10 +0300