C language string function summary

Posted by rtown on Mon, 17 Jan 2022 15:41:33 +0100

introduce

In the process of learning C language, the processing of strings is very frequent, but C language itself has no string type, so we need to use functions to facilitate our processing of strings.

● find the length of the string

        strlen

● string function with unlimited length

        strcpy

        strcat

        strcmp

● string functions with limited length

        strncpy

        strncat

        strncmp

Before understanding these functions, we should know that there is a hidden \ 0 behind the string, which takes up one byte of space

For example, in this program, we put "ABCD" into the arr array. Normally, four character data should occupy four bytes. However, we can see from the figure on the right that there is a "\ 0" after "D", which also accounts for one byte. This "\ 0" is the end of the string.

strlen function

Function declaration: size_t strlen (const char *string)

The argument to the strlen function is an address

Function principle: the function will start from the incoming address and will not stop until the "\ 0" behind the string is found. It will count while looking for it. After finding "\ 0", it will output the number on the counter

Note: if a character array is passed into the function, the result will be a random value, because after reading the contents of the array, the immediately following bit is not necessarily "\ 0", and will continue to look backward until "\ 0" is found

Implementation method of strlen function:

1 counter method:

#include<stdio.h>
#include<assert.h>
size_t my_strlen1(const char* str)//Counter method
{
	assert(str);
	int count = 0;//Define counter
	while (*str)
	{
		str++;
		count++;
	}
	return count;//Number on output counter
}
int main()
{
	char arr[] = "ABCD";
	int ret = my_strlen1(arr);
	printf("%d\n", ret);
	return 0;
}

2 recursion

#include<stdio.h>
#include<assert.h>
size_t my_strlen2(const char* str)
{
	assert(str);
	if (*str != '\0')
		return 1 + my_strlen2(str + 1);
	else
		return 0;
}
int main()
{
	char arr[] = "ABCD";
	int ret = my_strlen2(arr);
	printf("%d\n", ret);
	return 0;
}

3 pointer subtraction needle method

#include<stdio.h>
#include<assert.h>
size_t my_strlen3(const char* str)
{	
	assert(str);
	const char* end = str;//Assign the initial address to the pointer end and operate with end to ensure that str remains unchanged
	while (*end)
	{
		end++;
	}
	return end - str;//Subtract the initial address from the last address
}
int main()
{
	char arr[] = "ABCD";
	int ret = my_strlen3(arr);
	printf("%d\n", ret);
	return 0;
}

(note ①: size_t==unsigned int)

(note ②: when the string is used to transfer parameters, the initial address is actually uploaded)

strcpy function

Function declaration: char* strcpy(char* destination, const char* source)

The strcpy function will copy the contents of the source to the destination ("\ 0" will also be copied, but it will stop copying when it encounters "\ 0")

For example: char Arr1 [] = "differentiation";

           char arr2[]="SOURCE";

           strcpy( arr1,arr2 );

It is equivalent to that "\ 0" is advanced. At this time, when printing arr1 or calculating the string length, it will stop when it encounters \ 0.

If you put arr1 into arr2, the byte of arr1 is 12, while arr2 is 7 bytes. Arr2 cannot put 12 bytes. At this time, the program will make an error (cross-border access). Therefore, we should ensure that there is enough space to store the source string. The target string cannot be a constant string. The constant string is equivalent to a constant and cannot be modified.

Figure 1: before using strcpy Figure 2: after using strcpy

Note: 1, the source string must end with '\ 0'
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

Implementation of strcpy function

char* my_strcpy(char* destination,const char* source)//The return type is address
{
	assert(destination);
	assert(source);
	char* address = destination;//The address where the destination is stored
	while (*destination++ = *source++)
	{
		;
	}
	return address;//Return address, beginning and end echo
}

strcat function

Function declaration: char* strcat(char* dest, const char* src)

Copy the string pointed to by src (including "\ 0") after the string pointed to by DeST (delete "\ 0" at the original end of * dest). Ensure that * dest is long enough to accommodate the copied * src* The original characters in src remain unchanged. Returns a pointer to dest

So, can strcat be applied to the same string?

The answer is no, because it will replace the \ 0 of the source string and cause an endless loop

It should be noted that: 1. dest must have enough space to accommodate the src string.

2. After calling the function, "\ 0" at the end of * dest string is "\ 0" at the end of * src

Implementation of strcat function

char* my_strcat(char* dest, char* src)
{
	assert(dest);
	assert(src);
	char* p = dest;
	while (*dest)//Found destination string \ 0
	{
		dest++;
	}
	while (*dest++ = *src++)//Starting from \ 0 and entering src( SRC (\ 0) ) later will be replaced
	{
		;
	}
	return p;
}

strcmp function

Function declaration: int strcmp(const char* str1, const char* str2)

When STR1 < STR2, it returns a negative number;

When str1=str2, the return value = 0;

When STR1 > STR2, a positive number is returned.

That is, the two strings are compared character by character from left to right (compared according to the size of ASCII value) until different characters appear or '\ 0' is encountered.

Example: strcmp(str1,str2)

The ASCII code value of d is 100 and the ASCII code value of c is 99. According to the rules of the function, the returned number should be negative. Different compilers return different results. In vs environment, the return values are 1,0, - 1.

Implementation of strcmp function

#include<stdio.h>
#include<assert.h>
int my_strcmp(const char* str1, const char* str2)
{
	assert(str1&&str2);
	while (*str1 == *str2)
	{
		if (*str1 == '\0')     //be equal to
			return 0;
		str1++;
		str2++;
	}
	if (*str1 > *str2)
		return 1;        //greater than
	else
		return -1;      //less than 

}
int main()
{
	char arr1[] = "abcdef";
	char arr2[] = "abccdef";
	int ret = my_strcmp(arr1, arr2);
	printf("%d", ret);
	return 0;
}

strncpy function

Function declaration: char* strncpy(char* destination, const char* source, size_t num)

Means to copy the first num bytes of the string pointed to by source starting with the source address to the array pointed to by destination, and return the copied destination.

char dest[10] = "hello";

char stc[] = "bit";

strncpy(dest, src, 2);

What happens if the specified number of bytes to copy num is greater than the number of bytes in stc?

If we change num to 5

Lengthen dest string (more obvious effect)

char dest[10] = "helloabc";

char stc[] = "bit";

strncpy(dest, src, 5);

It can be seen that in this case, strncpy is equivalent to strcpy

As can be seen from the memory layout, if the length of the source string is less than num, after copying the source string, append 0 to the end of the target until num

Implementation of strncpy function

char* my_strncpy(char* dest, const char* src, int step)
{
	assert(dest);
	assert(src);
	char* p = dest;   //Save source address
	while (step)
	{
		if (*src != '\0')   //Judge whether the src content of the string has been copied
			*dest++ = *src++;
		else
			*dest++ = '\0';   //Make up \ 0 until it reaches step
		step--;
	}
	return p;   //Enter source address
}

strncat function

Function life: char* strncat(char* destination, const char* source, size_t num)

strncat() will copy n characters from the beginning of src string to the end of DeST string. Dest should have enough space to hold the string to be copied. If n is greater than the length of the string src, only the string content pointed to by src is appended to the end of dest. This is different from strncpy.

char dest[10] = "hello";

char src[] = "world";

strncat(dest, src, 3);

After hello, copy the three characters w # o # r to complement \ 0

 char dest [20]="hello\0ppppppppp";

char src[]="bit";

strncat(dest, src, 8);

Since all string functions are looking for \ 0, we add a \ 0 to the dest string to simulate the \ 0 after the string. It is not difficult to find that after the source string is copied, the target string will not be supplemented with \ 0 to 8 bytes.

When using this function, you should also ensure that the space of the target string can accommodate the number of bytes to be added

strncat function implementation

char* my_strncat(char* dest, char* src, int step)
{
	assert(dest && src);    //Assertion: ensure pointer validity
	char* p = dest;        //Save destination string address
	while (*dest)
	{
		dest++;
	}
	while (step && (*dest++ = *src++))
	{
		step--;
	}
	*dest = '\0';        //After copying the content, add \ 0 at the end of dest
	return p;        //Returns the destination string address
}

strncmp function

Function declaration: int strncmp (const char * STR1, const char * STR2, size_t n)

The function is to compare str1 and str2, and compare the first n bytes at most. If the first n characters of str1 and str2 are the same, 0 will be returned; If s1 is greater than s2, a value greater than 0 is returned; If s1 is less than s2, a value less than 0 is returned. The functions of strncmp and strcmp are basically similar and will not be repeated here

Implementation of strncmp function

int my_strncmp(const char* dest, const char* src, int step)
{
	assert(dest && src);        //Assertion to ensure pointer validity
	while (step)
	{
		if (*dest > *src)          //greater than
			return 1;
		else if (*dest < *src)        //less than
			return -1;
		else
		{
			dest++;        //dest pointer moves back to compare the next bit
			src++;        //The src pointer moves back to compare the next bit
			step--;        //Steps minus 1
		}
	}
	return 0;        //equal
}

It's over!

Need to update ha ~~

Topics: C C++ pointer string