[C language] character function and string function

Keywords: Java C C++ Back-end

catalogue

Find string length

1.strlen

String function with unlimited length

2.strcpy

3.strcat

4.strcmp

String function with limited length

5.strncpy,strncat,strncmp

String lookup

6.strstr

String cutting

7.strtok

Error message report

8.strerror

Memory operation function

9.memcpy

10.memmove

11.memcmp

12. memset

other

13. Some other string functions

1.strlen

size_t strlen ( const char * str );

Specific functions:

Find the length of the string.

Examples are as follows:

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


void main()
{
   char buffer[61] = "How long am I?";
   int  len;
   len = strlen( buffer );
   printf( "'%s' is %d characters long\n", buffer, len );
}

matters needing attention:

1. The string has' \ 0 'as the end flag. strlen function returns the number of characters before' \ 0 'in the string (excluding' \ 0 ').

2. The string pointed to by the parameter must end with '\ 0'.

3. Note that the return value of the function is size_t, which is unsigned (error prone)

eg.

#include <stdio.h>
int main()
{
 const char*str1 = "abcdef";
 const char*str2 = "abc";
 if(strlen(str2)-strlen(str1)>0)
 {
 printf("str2>str1\n");
 } 
 else
 {
 printf("srt1>=str2\n");
 }
 return 0;
}

Since strlen returns an unsigned number, when two unsigned numbers are calculated, the result is still an unsigned number. The unsigned number is greater than or equal to 0, so the final printed result is STR2 > STR1.

How can we modify it to compare?

if((int)strlen(str2)-(int)strlen(str1)>0)

It can be operated by strongly converting it to int type, or you can directly compare the size of the two

4. Constant strings can also be placed directly in strlen

eg.

int main()
{
	printf("%u", strlen("abc"));

	return 0;
}

Simulation Implementation:

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

2.strcpy

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

Specific functions:

Copy the string in the space indicated by Source (all characters from the beginning to the first encounter of \ 0, including \ 0) to the space indicated by DeST (the original string in dest will be overwritten), and then return char * Destination.

eg.

  We found that xxxxx in the original arr1 was replaced by hello Hello \ 0

matters needing attention:

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

eg.

2. The '\ 0' in the source string will be copied to the target space.

3. The target space must be large enough to store the source string.

4. The target space must be variable.  

Simulation Implementation:

char *my_strcpy(char *dest, const char*src)
{ 
 char *ret = dest;
 assert(dest != NULL);
 assert(src != NULL);
 
//First assign * src to * dest, and then both++
//If * src does not refer to \ 0, it is assigned to * dest, and then while determines that it is not 0 to continue the loop
//If * src refers to \ 0, it will also be assigned to * dest first, and then when it is judged to be 0, exit the loop
 while((*dest++ = *src++))
 {
   ;
 }
 return ret;
}

 3.strcat

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

Specific functions:

Append the content indicated by Source to the content indicated by Dest (from the first \ 0 of the string indicated by Dest to the first \ 0 of the content indicated by Source), and finally return the starting address of Dest.

eg.

  matters needing attention:

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

2. The target space must be large enough to accommodate the contents of the source string.

3. The target space must be modifiable.

Simulation Implementation:

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;
}

4.strcmp

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

Specific functions:

If the first string is greater than the second string, a number greater than 0 is returned;

If the first string is equal to the second string, 0 is returned;

If the first string is less than the second string, a number less than 0 is returned.

Two character arrays are compared character by character, and the ASCII code values of two characters are compared. STR1 > STR2 returns a number greater than zero, str1=str2 returns 0, and STR1 < STR2 returns a number less than 0. (stop after comparing the \ 0 of any string)

eg.

matters needing attention:

1.strcmp compares string contents, not length.

Simulation Implementation:

int my_strcmp(const char* s1, const char* s2)
{
	assert(s1 && s2);

	while (*s1 == *s2)
	{
		if (*s1 == '\0')
			return 0;
		s1++;
		s2++;
	}

	return *s1 - *s2;
}

5.strncpy,strncat,strncmp

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

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

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

Specific functions:

Like strcpy, it only limits the length of the copy to ensure security.

matters needing attention:

1. If the length of the source string is less than count, after copying the source string, append \ 0 to the end of the target until count.

eg.

Specific functions:

Like strcat, it only limits the additional length to ensure security.

matters needing attention:

1. After appending count strings in Source to Dest, a \ 0 will be appended automatically.

2. When appending, the \ 0 appended to the Source will automatically stop regardless of the count.

Specific functions:  

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

6.strstr

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

Specific functions:

Find the string indicated by CharSet in the string indicated by string, and return the address where CharSet first appears in string; if not found, return NULL.

eg.

matters needing attention:

1. If there are multiple CharSet strings in the string, only the first address will be returned

Simulation Implementation:

char* my_strstr(const char*str1, const char* str2)
{
	assert(str1 && str2);
	//
	char* s1;
	char* s2;
	char* cp = str1;
	
	if (*str2 == '\0')//System regulations, negligible
		return str1;

	while (*cp)
	{
		s1 = cp;
		s2 = str2;

		//while (*s1!='\0'  && *s2 != '\0' && *s1 == *s2)
		while (*s1 && *s2 && *s1 == *s2)
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')//Stop when \ 0 is found
		{
			return cp;
		}
		cp++;
	}

	//can't find
	return NULL;

7.strtok

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

  Specific functions:

1. The Del parameter is a string that defines the set of characters used as separators. The first parameter specifies a string that contains 0 or more tags separated by one or more separators in the sep string.

2. The strtok function finds the next tag in the Token, ends it with \ 0, and returns a pointer to this tag. (the test result under vs is to return a pointer to the string in front of the tag) (Note: the strtok function will change the string to be operated on, so the string segmented by the strtok function is generally a temporary copy of the content and can be modified.)

3. The first parameter of strtok function is not NULL. The function will find the first tag in str, and strtok function will save its position in the string.

4. The first parameter of strtok function is NULL. The function will start at the saved position in the same string to find the next tag.

5. If there are no more tags in the string, a NULL pointer is returned.

eg.

 8.strerror

char * strerror ( int errnum );

Specific functions:

Returns the error information corresponding to the error code.

When the C language library function call fails, the error code will be stored in the errno variable.

eg.

Error messages can also be printed with perror

9.memcpy

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

Specific functions:

The memcpy function copies count bytes of data back from the src location to the destination memory location. (data memory is not limited)

eg.

  

matters needing attention:

1. This function will not stop when it encounters' \ 0 '.

2. If there is any overlap between source and destination, the copied result is undefined.

Simulation Implementation:

void* my_memcpy(void* dest, const void*src, size_t count)
{
	void* ret = dest;
	assert(dest && src);

	while (count--)
	{
		*(char*)dest = *(char*)src;
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}
	return ret;
}

10.memmove

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

Specific functions:

The difference from memcpy is that the source memory block and target memory block processed by the memmove function can overlap.

If the source space and target space overlap, you have to use the memmove function.

eg.

Simulation Implementation:

void* my_memmove(void* dest, const void* src, size_t count)
{
	void* ret = dest;
	assert(src && dest);

	if (dest < src)
	{
		//Front - > rear
		while (count--)
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		//Rear - > front
		while (count--)
		{
			*((char*)dest+count) = *((char*)src + count);
		}
	}

	return ret;
}

11.memcmp

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

Specific functions:

Compare the count bytes starting from the buf1 and buf2 pointers.

eg.

  Try to emulate the previous simulation implementation to realize memcmp

12. memset

Specific functions:

Set count bytes in dest to c

eg.

13. Some other string functions

Character classification function:

Character conversion function:

int tolower ( int c );//Converts a given letter to lowercase
int toupper ( int c );//Converts a given letter to uppercase

gets: string input

puts: string output

atof, atoi: convert string to numeric value

sprint, sscanf: string format input, output

 

The above is the content of this sharing. If you like my sharing, don't forget to praise and pay attention!

If you have any comments on my article, please comment below or send me a private letter!

I'm Bai Chen. I'll see you next time!!

Posted by Wayne Herbert on Thu, 18 Nov 2021 22:19:23 -0800