C language -- common string functions and their simulation implementation

Posted by tomhath on Tue, 28 Dec 2021 18:54:09 +0100

preface

The C library provides multiple functions for processing strings. ANSI C places the prototypes of these functions in string H header file. The most commonly used functions are strlen(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), and strncpy(). In addition, there is the sprintf() function, whose prototype is stdio H header file.

1, strlen() function

The strlen() function counts the length of a string.

int strlen(char const*string);

Gets the length of the string, returns the number of characters, but does not include '\ 0' (Terminator).

#include<stdio.h>
#include<string.h>
int main()
{
	char arr[] = "This is strlen function!";
	printf("%d\n",strlen(arr));
	return 0;
}

Output example:

24

Simulated strlen function implementation:

#include<stdio.h>
#include<assert.h>
int myStrlen(const char* arr)
{
	int n = 0;
	assert(arr);
	while (*arr != '\0')
	{
		n++;
		arr++;
	}
	return n;
}

2, strcat() and strncat() functions

Both strcat() and strncat() functions connect the string pointed to by str2 to the character pointed to by str1, delete '\ 0' after str1, and return the first address of the string pointed to by str1.
2.1 strcat() function
The strcat() (used to splice strings) function takes two strings as parameters. The function appends the backup of the second string to the end of the first string, and takes the new string formed after splicing as the first string, and the second string remains unchanged.

char* strcat(char *string1,char *string2);

The type of strcat() function is char * (that is, a pointer to char). The strcat() function returns the first parameter, that is, the address of the first string after splicing the second string. The source character must end with '\ 0' and the destination space must be large enough to hold the source string.

char arr1[10]="abc";
	char arr2[] = "def";
	strcat(arr1, arr2);
	printf("%s\n", arr1);
	printf("%s\n", arr2);

Output example:

abcdef
def

Simulated strcat function implementation:

void myStrcat(char* arr1,char* arr2)
{
	assert(arr1 != NULL);
	assert(arr2 != NULL);
	while (*arr1 != '\0')
	{
		arr1++;
	}
	while (*arr2 != '\0')
	{
		*arr1 = *arr2;
		arr1++;
		arr2++;
	}
}

2.2 strncat() function
The strcat() function cannot check whether the first array can hold the second string. If the space allocated to the first array is not large enough, there will be a problem when the extra characters overflow to the adjacent storage units. The strncat() function can solve this problem. The strncat function can connect the string str2 (source) to the string str1 (target). count determines how many characters you want to connect in str2. Of course, note that the space of str1 (target) should be large enough to receive connected characters.

char *strncat( char *str1, const char *str2, size_t count );

The third parameter of the function specifies the maximum number of characters added.

char arr1[10]="abc";
	char arr2[] = "def";
	strncat(arr1, arr2, 3);
	printf("%s\n", arr1);

3, strcmp() and strncmp() functions

The two functions are compared according to ASCII code and judged by the return value of the function:
1. Return 0, string 1 equals string 2;
2. Greater than 0, string 1 greater than string 2;
3. Less than 0, string 1 less than string 2.
3.1 strcmp() function

int strcmp(const char * _Str1,const chart* _Str2);

This function compares strings through comparison operators, just as it compares numbers. If the two string parameters are the same, the function returns 0; If string 1 is greater than string 2, a value greater than zero is returned; If string 1 is less than string 2, a value less than zero is returned. Note that this is case sensitive, and the ASCII codes of "ABC" and "ABC" are different.

/* Program 3.1 - the program can run normally */
#include<stdio.h>
#include<string.h>
#define STR "ABC"
#define STRLEN 40
int main()
{
	char word[STRLEN];
	gets_s(word, STRLEN);
	puts(word);
	while (strcmp(word, STR) != 0)
	{
		puts("No, that's wrong. Try again.");
		fgets(word, STRLEN, stdin);
	}
	puts("That's right!");
	return 0;
}

The StrCmp () function compares strings, not the entire array, which is a very good function. Although the array word takes up 40 bytes and the "ABC" stored in it only takes up 4 bytes (there is another empty character '\ 0'), the strcmp() function will only compare the part before the first empty character in word. Therefore, you can use StrCmp () to compare strings stored in arrays of different sizes.
Simulate the implementation of strcmp function:

int myStrcmp(const char* str1,const char* str2)
{
	while (*str1!='\0'&&*str2!='\0')
	{
		int x = *str1 - *str2;
		if (x == 0)
		{
			str1++;
			str2++;
		}
		else
		{
			return x;
		}
	}
	if (*str1 == '\0' && *str2 == '\0')
	{
		return 0;
	}
	else
	{
		if (*str1 == '\0' && *str2 != '\0')
			return -1;
		else
			return 1;
	}
}

3.2 strcnmp() function
The strcmp() function compares characters in a string until different characters are found, which may continue until the end of the string. When comparing two strings, the strncmp() function can compare different characters, or only the number of characters specified by the third parameter.

int strncmp(const char*str1,const char *str2,int size);

For example, to find a string that starts with "astro", you can restrict the function to find only these five characters. Program 3.2 demonstrates the use of this function.

/* Procedure 3.2 -- using strncmp() */
#include <stdio.h>
#include <string.h>
#define LISTSIZE 6
int main()
{
const char * list[LISTSIZE] ={
"astronomy", "astounding",
"astrophysics", "ostracize",
"asterism", "astrophobia"
};
int count = 0;
int i;
for (i = 0; i < LISTSIZE; i++)
if (strncmp(list[i], "astro", 5) == 0)
{
printf("Found: %s\n", list[i]);
count++;
}
printf("The list contained %d words beginning"" with astro.\n", count);
return 0;
}

Output example:

Found: astronomy
Found: astrophysics
Found: astrophobia
The list contained 3 words beginning with astro.

4, strcpy() and strncpy() functions

char *strcpy(char*des,char*src);
char *strncpy(char *des,char *src,int size);

strcpy() and strncpy() functions copy the string pointed to by src to the string array pointed to by des. The size parameter in strncpy() function can also copy the string with specified length. des is recommended to be a character array.
Note: try to use character array for the target, because if it is a character pointer, the allocated memory is in the constant pool and cannot be changed, which is easy to cause segment errors.
4.1 strcpy() function
Copy the string pointed to by src to the string array pointed to by des, and the * * terminator is copied together** If the operation is successful, this character (the address of des) is returned
Note: the target space must be large enough to store the source string.

char *strcpy(char*des,char*src);

strcpy() accepts two string pointers as parameters, and can declare src as pointer, array name or string constant; The des pointer should point to a data object (such as an array), and the object has enough space to store a copy of the source string. * * if DES is not initialized, the string pointed to by src may be copied anywhere! * * remember, the declaration array will allocate the space for storing data, while the declaration pointer only allocates the space for storing one address.

#include<stdio.h>
#include<string.h>
#define STRLEN 40
#pragma warning(disable:4996)
int main()
{
	char des[STRLEN];
	char src[STRLEN]="This is strcpy function!";
	char* temp;

	temp=strcpy(des, src);

	puts(des);
	puts(temp);
	return 0;
}

Output example:

This is strcpy function!
This is strcpy function!

Implementation of simulated strcpy function:

#include<stdio.h>
#include<assert.h>
char* myStrcpy(char* str1,const char* str2)
{
	assert(str1 != NULL);
	assert(str2!=NULL);
	while (*str2 != '\0')
	{
		*str1 = *str2;
		str1++;
		str2++;
	}
	*str1 = *str2;//Copy '\ 0' in the source string to the destination space
	return str1;
}

4.2 strncpy() function
The strcpy() function cannot check whether the target space can accommodate a copy of the source string. Copying strings is safer with strncpy(), and the third parameter of this function indicates the maximum number of characters that can be copied.

char *strncpy(char *des,char *src,int size);

Copy the string pointed to by src to the string array pointed to by des. The length of the copied string depends on the size parameter. The terminator '\ 0' may not be copied (copy the size characters in src or the characters before the empty characters (which conditions are met first) to des).

#include<stdio.h>
#include<string.h>
#define STRLEN 40
#pragma warning(disable:4996)
int main()
{
	char des1[STRLEN];
	char des2[STRLEN];
	char src[STRLEN]="This is strncpy function!";
	char* temp1;
	char* temp2;

	temp1=strncpy(des1, src, STRLEN);
	temp2 = strncpy(des2, src, 5);//Terminator '\ 0' was not copied
	puts(des1);
	puts(temp1);
	puts(des2);
	puts(temp2);
	return 0;
}

Output example:

This is strncpy function!
This is strncpy function!
This Hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot his is strncpy function!
This Hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot his is strncpy function!

If the length of the string copied to the target space is less than the length of the source string or the target space cannot hold the copied copy, set the last element of the target space to a null character.

5, sprintf() function

The sprintf() function is declared in stdio H, not string H medium. This function can combine multiple elements into a string, and the first parameter of sprintf() is the address of the target string. The other parameters are the same as printf(), that is, the format string and the list of items to be written. Returns the length of the buffer.

int sprintf( char *buffer, const char *format [, argument,...] );
#include<stdio.h>
#include<string.h>
#include<assert.h>
#define STRLEN 40
#pragma warning(disable:4996)
int main()
{
	char des[2*STRLEN];
	char src[STRLEN]="This is sprintf function";
	int i=sprintf(des,"%s %s %d",src,src,521);
	printf("%d\n", i);
	puts(des);

	return 0;
}

Topics: C Back-end