Several common string operation functions (strlen, strcpy, strcmp, strcat, strstr, strtok, strerror, strncpy, strncmp, strncat)

Posted by sweyhrich on Fri, 24 Sep 2021 10:28:34 +0200

We all know that C language provides us with many built-in library functions, and these library functions need to refer to their respective header files when they are used.

This article is about several string related functions in < string. H >.

catalogue

1.strlen() - count the number of characters in the string

one point one   strlen provided by C language

  1.2 simulation of strlen library functions

  2.strcpy() - string copy function

two point one   strcpy provided by C language

2.2 Simulated Implementation of strcpy library function

3.strcat() - string append function

  3.1 strcat provided by C language

  3.2 Simulated Implementation of strcat library functions

4. strcmp() - string comparison function

4.1 strcmp provided by C language

4.2 Simulated Implementation of strcmp function

5. strstr()—   Find source string in destination string

5.1 STR provided by C language

5.2 Simulated Implementation of STR library functions

  6. strtok() - string separator function

six point one   strtok provided by C language

  6.2 Simulated Implementation of strtok library functions

7. strerror()—   You can return the error information corresponding to the built-in error code in C language

1.strlen() - count the number of characters in the string

one point one   strlen provided by C language

Function declaration:

size_t strlen( const char *string );

Specific examples:

//strlen instance
#include<stdio.h>
#Include < string. H > / / header file
int main()
{
	char str1[] = "abcd\0efgh"; //Put a \ 0 in the middle. Will the test stop when the statistics come here
	char str2[] = { 'a','b','c','d'}; //Do not put end of string flag - '\ 0'
	size_t ret1 = strlen(str1); //Number of received statistics
	size_t ret2 = strlen(str2);
	printf("%u\n", ret1);      //size_ T: unsigned int, so use% u to print
	printf("%u\n", ret2);

	return 0;
}

The operation results are as follows:

  Summary: strlen (count string length) this function will count the number of characters until '\ 0'. For str1, I   A '\ 0' flag is given after the d character in advance, so the value of ret1 is 4. In the str2 character array, I didn't give '\ 0', so strlen will count back until it meets' \ 0 ', so the value of ret2 is a random value, because we can't know where the' \ 0 'behind the array is.

  1.2 simulation of strlen library functions

  Above, we know the declaration and use of the library strlen function. Next, we will personally implement a my_strlen function, and let it implement the C language standard for strlen function.

First, although we don't know how strlen in the library is implemented, we can refer to the declarations it provides.

my_strlen function declaration:

size_t my_strlen(const char* str); //It can be designed directly according to the original declaration

Then is the concrete implementation. We can use the pointer offset to access each character of the string. If the character is' \ 0 ', it ends.

my_strlen function definition:

//Simulated implementation of strlen library function
#include<stdio.h>
#Include < assert. H > / / the header file of the assertion.
size_t my_strlen(const char* str)  // const modifier so that the original string will not be modified.
{
	assert(str);      //Assertion: an error is reported for a null pointer (NULL).
	size_t count = 0; //size_t type to make it consistent with the return type.
	while (*str++)    //First determine whether it is' \ 0 ', and then offset.
	{
		count++;
	}
	return count;
}
int main()
{
	char str1[] = "abcd\0efgh";        //Advance to \ 0
	char str2[] = { 'a','b','c','d' }; //Hold \ 0
	size_t ret1 = my_strlen(str1);   
	size_t ret2 = my_strlen(str2);
	printf("%u\n", ret1);     
	printf("%u\n", ret2);

	return 0;
}

The operation results are as follows:

  The result at this time is the same as that above, which shows that we use my_strlen implements the function of strlen function.

  2.strcpy() - string copy function

two point one   strcpy provided by C language

Function declaration:

char *strcpy( char *strDestination, const char *strSource );

Function instance:

//strcpy - string copy function
//example
#include<stdio.h>
#include<string.h>
int main()
{
	char arr1[] = "abcdef";
	char arr2[] = "xxxxxxxxxxxxxx";
	char* p = strcpy(arr2, arr1);
	printf("%s\n", p);

	return 0;
}

The operation results are as follows:

  Summary: from the above examples and running results, we can see that strcpy library function will copy '\ 0' in the source string to the target string when copying

  Go, so the print result is abcdef, and the following x is not printed.

In addition, our library function also has an n-added string copy function - strncpy. Compared with strcpy, this function only has one more parameter (the number of characters to be copied).

//strncpy declaration
char *strncpy( char *strDest, const char *strSource, size_t count );

//strncpy example
//When the number of data copied by count is greater than the number in the Source string, it is supplemented with '\ 0'
#include<stdio.h>
#include<string.h>
int main()
{
	char arr1[] = "abcdefgh";
	char arr3[] = "abcdefgh";
	char arr2[] = "xxxx";

	char* p1 = strncpy(arr1, arr2, 2);
	printf("%s\n", p1);
	char* p2 = strncpy(arr3, arr2, 6);   //Exceed, supplement '\ 0'
	printf("%s\n", p2);

	return 0;
}

Therefore, this function is more flexible and safer when used.

If you are interested, you can study it by yourself.

2.2 Simulated Implementation of strcpy library function

As above, we can also borrow its declaration when simulating the implementation of strcpy library function.

my_strcpy function declaration:

char* my_strcpy( char* dest, const char* src );

Then it is implemented. The principle is also very simple, that is, a byte by byte copy through loop and pointer offset.

my_strcpy function definition:

//Simulated implementation of strcpy library function
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest,const char* src)
{
	assert(dest && src);   //Assertion, avoid null pointers
	char* ret = dest;
	while (*dest++ = *src++)
	{
		;
	}
	return ret;    //Return destination address
}
int main()
{
	char arr1[] = "abcdef";
	char arr2[] = "xxxxxxxxxxxxxx";
	char* p = my_strcpy(arr2, arr1);
	printf("%s\n", p);

	return 0;
}

Operation results:

  At this time, when we compare the running results, we will find that we have completed a simulated strcpy function.

3.strcat() - string append function

  3.1 strcat provided by C language

Function declaration:

char *strcat( char *strDestination, const char *strSource );

Function instance:

//Example 1
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[50] = "abc\0abc";
	strcat(str1, "def");
	printf("%s\n", str1);
		
	return 0;
}
//Example 2
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[50] = "abc\0abc";
	strcat(str1, str1);      //Add to yourself
	printf("%s\n", str1);
		
	return 0;
}

Operation results:

Summary: through the above operation result diagram, you can see that both additions are successful, indicating that strcat can be added not only by others, but also by yourself.

Like strcpy, it also has a similar but safer library function - strncat. Compared with the original function, this library function only adds one parameter (the number of characters to be added). Its usage is roughly the same as that of strcat, but it is more flexible.

//strncat declaration
char *strncat( char *strDest, const char *strSource, size_t count );

//strncat example
#include<stdio.h>
#include<string.h>
int main()
{
	char arr1[50] = "abc\0xxxxxxxxxxxx";
	char arr2[] = "defgh";
	strncat(arr1, arr2, 8);  //Append from the first '\ 0'.
	printf("%s\n", arr1);
	return 0;
}

There is no more detail here.

  3.2 Simulated Implementation of strcat library functions

  First, we also refer to the function declaration of strcat.

my_strcat function declaration:

char* my_strcat( char* dest, const char* src );

Then there is implementation.

my_strcat function definition:

//Simulation implementation my_strcat function
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* dest, const char* src)
{
	assert(dest && src);
	char* ret = dest;
	while (*dest)
	{
		dest++;
	}
	while (*dest++ = *src++)
	{
		;
	}
	return ret;
}
int main()
{
	char str1[20] = "abc";   //Incomplete initialization
	char str2[] = "def";
	char* ret = my_strcat(str1, str2);
	printf("%s\n", ret);
	return 0;
}

Operation results:

  Here, my_strcat is also successfully simulated.

4. strcmp() - string comparison function

4.1 strcmp provided by C language

  Function declaration:

int strcmp( const char *string1, const char *string2 );

  Function instance:

//strcmp - string comparison function
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[] = "abcdef";
	char str2[] = "abc";
	int ret = strcmp(str1, str2);
	if (ret > 0)
	{
		printf(">");
	}
	else if (ret < 0)
	{
		printf("<");
	}
	else
	{
		printf("=");
	}
	return 0;
}

Operation results:

Summary: when strcmp compares the size of strings, it starts from the first character of each string and compares one by one. If STR1 > STR2 is different, it returns a number greater than 0. On the contrary, it returns a number less than 0.

Here, the library function strcmp has the same function, but a safer library function - strncmp. The library function only adds one parameter (the number of characters to be compared).

//strncmp declaration
int strncmp( const char *string1, const char *string2, size_t count );

//strncmp example
#include<stdio.h>
#include<string.h>
int main()
{
	char arr1[] = "abcdefgh";
	char arr2[] = "abcd";
	int ret = strncmp(arr1, arr2, 4);
	if (ret > 0)
	{
		printf(">\n");
	}
	else if (ret < 0)
	{
		printf("<\n");
	}
	else
	{
		printf("=\n");
	}

	printf("%d\n", ret);
	return 0;
}

The usage is basically the same, but more flexible.

There will be no more introduction here.

4.2 Simulated Implementation of strcmp function

First, refer to the function declaration of the library function.

my_strcmp function declaration:

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

my_strcmp function definition:

//Simulated implementation of strcmp library functions
#include<stdio.h>
#include<assert.h>
int my_strcmp(const char* str1, const char* str2)
{
	assert(str1 && str2);
	while (*str1 == *str2 && *str1)
	{
		str1++;
		str2++;
	}
	return *str1 - *str2;
}
int main()
{
	char str1[] = "abc";
	char str2[] = "abcdef";
	int ret = my_strcmp(str1, str2);
	if (ret > 0)
	{
		printf(">\n");
	}
	else if (ret < 0)
	{
		printf("<\n");
	}
	else
	{
		printf("=\n");
	}
	printf("%d\n", ret);  //Print it, my_ Return value of StrCmp
	return 0;
}

Operation results:

  After reviewing the results, we know that strcmp has been simulated successfully.

5. strstr()—   Find source string in destination string

5.1 STR provided by C language

Function declaration:

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

  Function instance:

//strstr - finds the source string in the destination string
//When found, it returns the address of the source string in the target string; otherwise, it returns NULL
#include <stdio.h>
#include <string.h>
int main()
{
	char str[] = "This is a simple string";
	char* ret = strstr(str, "simple");
	if (ret == NULL)
	{
		printf("String not found!\n");
	}
	else
	{
		printf("%s\n", ret);
	}
	return 0;
}

Operation results:

  Summary: the strstr library function can help us check whether there is a substring we need in a string. At the same time, as long as it is found, it will return the address of that substring for the first time in the total string.

Next, the simulation is implemented.

5.2 Simulated Implementation of STR library functions

Function declaration:

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

Definition of function:

//Simulated implementation of STR library function
#include <stdio.h>
#include<assert.h>
const char* my_strstr(const char* str1, const char* str2)
{
	assert(str1 && str2);
	while (1)
	{
		const char* p = str1;
		const char* q = str2;
		while (*p == *q && *p != '\0' && *q != '\0')
		{
			p++;
			q++;
		}
		if (*q == '\0')
		{
			return str1;
		}
		else if (*str1 == '\0')
		{
			return NULL;
		}
		str1++;
	}
}
int main()
{
	char str[] = "This is a simple string";
    const char* ret = my_strstr(str, "simple");
	if (ret == NULL)
	{
		printf("String not found!\n");
	}
	else
	{
		printf("%s\n", ret);
	}
	return 0;
}

Operation results:

  It should be noted here that since we want to set the parameters of the user-defined function as the same as those of the library function, we use const to modify str1. Later, when returning str1, the return value type of the function should be written as const char *, so that there will be no warning. Similarly, when receiving, it should also be written as a pointer of const char * type.

  6. strtok() - string separator function

six point one   strtok provided by C language

Function declaration:

char *strtok( char *strToken, const char *strDelimit );

Function instance:

//strtok() - string separator function
#include<stdio.h>
#include<string.h>
int main()
{
	char str[] = "This is a simple string";
	char seq[] = " ";         //The string used to store the delimiter

	char str1[200] = { 0 };   //The strtok function changes the contents of the source string
	strcpy(str1, str);        //So make a copy for use

	//The strtok function only needs to pass in the first address of the target string when it is used for the first time,
	//In the future, it will remember the address of the first character after the separator, and after each separation, it will
	//The address of the first element of the delimited string is returned

	for (char* ret = strtok(str1, seq); ret != NULL; ret = strtok(NULL, seq))
    //This function is especially easy to use with the for loop. After all the used are separated, it will return a NULL
	{
		printf("%s\n",ret);
	}

	return 0;
}

Operation results:

Summary: the strtok function allows us to separate the parts we need in a string (according to which character we want to use as the boundary). It should be noted that before separation, we need to copy the source string to avoid changing the content of the source string.

  6.2 Simulated Implementation of strtok library functions

my_strtok function declaration:

char* my_strtok(char* str,const char* seq);

my_strtok function definition:

//Simulation implementation my_strtok
#include<stdio.h>
#include<string.h>
#include<assert.h>
char* my_strtok(char* str,const char* seq)
{	
	assert(seq);
	static char* Q = "abc";         //Arbitrarily point to a string of constant strings to avoid wild pointers
	if (*Q == '\0')                 //Finished separating all strings
	{
		return NULL;
	}     
	if (str != NULL)                //When executing strtok for the first time, go if, otherwise go else
	{
		char* ret = str;            //Save a copy of the starting coordinates
		char* w = str;
		while (*w != '\0')
		{
			const char* temp = seq; //Used to traverse the separator string
			while (*temp != '\0')
			{
				if (*w != *temp)   //ergodic
				{
					temp++;       
				}
				else               //A delimited string was found
				{
					*w = '\0';     //Separator set to '\ 0'
					Q = w + 1;     //Put the address of the first element of the next string into Q
					return ret;    //Returns the address of the first element of a delimited string
				}
			}
			w++;
		}
		Q = w;                    //Give Q the address of '\ 0' at the end of the string, indicating that the string separation is complete.
		return ret;               //Returns the address of the first element of the current string
	}
	else
	{
		char* ret = Q;           //Copy a first element address
		char* w = Q;             //Give the address of the first element of the next string stored in Q to w              
		while (*w != '\0')
		{
			const char* temp = seq;
			while (*temp != '\0')
			{
				if (*w != *temp)
				{
					temp++;
				}
				else
				{
					*w = '\0';
					Q = w + 1;
					return ret;
				}
			}
			w++;
		}
		Q = w;
		return ret;
	}
}

int main()
{
	char str[] = "This is a simple string";
	char seq[] = " ";         //The string used to store the delimiter

	char str1[200] = { 0 };   //The strtok function changes the contents of the source string
	strcpy(str1, str);        //So make a copy for use

	//The strtok function only needs to pass in the first address of the target string when it is used for the first time,
	//In the future, it will remember the address of the first character after the separator, and after each separation, it will
	//The address of the first element of the delimited string is returned

	for (char* ret = my_strtok(str1, seq); ret != NULL; ret = my_strtok(NULL, seq))
		//This function is especially easy to use with the for loop. After all the used are separated, it will return a NULL
	{
		printf("%s\n", ret);
	}

	return 0;
}

Operation results:

  After completing the simulation of strtok function, there is only one function strerror function left

7. strerror()—   You can return the error information corresponding to the built-in error code in C language

  Function declaration:

char *strerror( int errnum );

Function instance:

//strerror() - you can return the error information corresponding to the built-in error code in C language
#include<stdio.h>
#include<string.h>
int main()
{
	printf("%s\n", strerror(-1));// Unknown error
	printf("%s\n", strerror(0));// No error
	printf("%s\n", strerror(1));// Operation not permitted
	printf("%s\n", strerror(2));// No such file or directory
	printf("%s\n", strerror(3));// No such process
	printf("%s\n", strerror(4));// Interrupted function call
	printf("%s\n", strerror(5));// Input / output error

	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));   //Errno - a built-in global variable that stores error code information in C language
		perror("test");//Print: + error message
	}
	else
	{
		printf("File opened successfully\n");
	}
	return 0;
}

We won't talk about strerror simulation here. For this function, we can know how to use it. In addition to this function, perror function can also help us print error code information, but it is forced printing. If you are interested, you can go on to study it. This article is all about it.

Topics: C