Introduction and Partial Realization of String Functions in C Language

Table of contents

1: Function with unlimited string length

(1) strlen ( ) function

(2) strcpy ( ) function

(3) strcat ( ) function

(4) strcmp ( ) function

Two: Functions with limited character length

(1) strncmp ( ) function

(2) strncpy ( ) function

(3) strncat ( ) function

Three: several other functions

(1) strstr ( ) function

(2) strerror ( ) function

(3) strtok( ) function


1: Function with unlimited string length

(1) strlen ( ) function

Function: Calculate the length of a string. (not including the trailing '\0')

Implementation principle: We all know that the end mark of a string is '\0' , and the strlen( ) function traverses the entire array through the first address of the string, and ends when it encounters '\0' .

Call: Pass in the first address of the string, as shown in the figure below

 

Implementation idea:

[1] There are many methods, but most of them rely on pointers to traverse . We can define a function my_strlen () , the function parameter is the first address of the string (char*) . (Because it is only to calculate the length, to prevent the content of the string from being changed, you can add const to char* for modification )

[2] We can design a counter and use a while loop to traverse the string . If '\0' is not encountered, the counter will be incremented by one , and the loop will continue. Otherwise, the loop will end and the counter value will be returned . (It is also possible to design a head pointer and a tail pointer, and subtract the two pointers to get the number of elements between the pointers)

Illustration:

code:

 

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <string.h>
/长度加测试
//注意const修饰,防止改变原字符串内容
int my_strlen(const char* str)
{
    //断言,不传空指针
    assert(str);
    //计数器
	int count = 0;
    //如果走到'\0',结束
	while (*str)
	{
		str++;
		count++;
	}
	return count;
}

int main()
{
	char str[20] = "hello";
	printf("%u\n", strlen(str));
	return 0;
}

(2) strcpy ( ) function

Function: Copy all the contents of a string to the target string . (including '\0') 

Implementation principle: Pass in the first address of the target string and source string , copy the content of the source string to the target string in turn with '\0' as the end mark , and finally return the first address of the modified string.

Call: Pass in the first addresses of two strings, the first parameter is the first address of the target string, and the second parameter is the first address of the source string , as shown in the figure below

Implementation idea:

【1】Define a function my_strcpy( ) , whose parameter is the first address of two character strings. (Note: The target string is to be modified. In order to prevent the source string from being modified, it can be modified by adding const )
[2] Traversing the source string , assigning the content of the source string to the target string until the ' \0' is also assigned to the target string, and finally returns the first address of the modified string.

Illustration:

 code:

//复制加测试
char* my_strcpy(char* dest, const char* src)
{
	//断言,不传空指针
	assert(dest&&src);
	char* cmp = dest;
	//如果遇到'\0',*dest++='\0',结束循环
	//*dest++的值为*dest,结束后dest指针加1
	while (*dest++=*src++)
	{
		;
	}
	return cmp;
}

int main()
{
	char str1[20] = "bayuhao";
	char str2[20] = "hello";
	printf("%s\n", str1);
	printf("%s\n", my_strcpy(str1, str2));
	return 0;
}

(3) strcat ( ) function

Function: Append the content of another string after one string.

Realization principle: strlen( ) function plus strcpy( ) function , first traverse the target string to '\0' , and then assign the content of the source string to the content behind the target string.

Call: Pass in the first address of two strings, the first parameter is the first address of the target string, and the second parameter is the first address of the source string , as shown in the figure below

code:

 

//追加和测试
//为了避免修改源字符串,用const修饰
char* my_strcat(char* dest,const char* src)
{
	char* ret = dest;
  //断言,不传空指针
	assert(dest && src);
	while (*dest)
	{
		dest++;
	}
	while (*dest++=*src++)
	{
		;
	}
	return ret;
}
int main()
{
	char str1[20] = "hello ";
	char str2[] = "world";
	printf("%s\n", str1);
	printf("%s\n", my_strcat(str1, str2));
	return 0;
}

(4) strcmp ( ) function

Function: Perform string comparison, return 1 if the former is greater than the latter, return -1 if the latter is greater than the former, and return -1 if the latter is the same (you can also return a number greater than 0 or less than 0 to indicate the size relationship, and the implementation of different platforms is different) .

String comparison: starting from the first character, compare them sequentially , and compare the ASCLL codes of the two when encountering different characters . The larger one is the larger string, and the smaller one is the smaller string . Going to '\0' at the same time means that the two strings are the same.

Implementation principle: traverse through two string pointers, and compare them in turn.

Call: Pass in the first addresses of two strings to be compared, as shown in the figure below

code:

 

//比较和测试
//只是进行比较,用const进行修饰防止修改字符串内容
int my_strcmp(const char* s1,const char* s2)
{
    //断言,不传空指针
	assert(s1 && s2);
	//以单个字符不相同为循环结束条件
	while (*s1 == *s2)
	{
		if (*s1 == '\0')
			return 0;
		s1++;
		s2++;
	}
	//返回两者相差的ASCLL码
	return *s1 - *s2;
}
int main()
{
	char str1[20] = "hello";
	char str2[20] = "hellp";
	char str3[20] = "hello";
	int ret = strcmp(str1, str2);
	int ret1 = strcmp(str1, str3);
	printf("ret:%d\n", ret);
	printf("ret1:%d\n", ret1);
	return 0;
}

Two: Functions with limited character length

(1) strncmp ( ) function

Function: It also compares strings, but there is one more parameter, and only fixed n bits are compared.

Implementation principle: Perform a fixed number of comparisons based on the parameters passed in .

Call: Give the first addresses of two strings, and add an integer , as shown in the figure below

 

 code:

//固定比较n位
int my_strncmp(const char* str1, const char* str2, int num)
{
  //断言,不传空指针
	assert(str1 && str2);
	for (int i = 0; i < num; i++)
	{
		//如果不同,就计算相差的大小
		if (*str1 != *str2)
		{
			return *str1 - *str2;
		}
		//迭代,往后走
		str1++;
		str2++;
	}
	return 0;
}
int main()
{
	char str1[20] = "helloq";
	char str2[20] = "hellop";
	int ret=my_strncmp(str1, str2, 5);
	if (ret > 0)
		printf("str1大于str2\n");
	else if (ret < 0)
		printf("str1小于str2\n");
	else
		printf("str1和str2相同\n");
	return 0;
}

(2) strncpy ( ) function

Function: Similar to the strcpy( ) function, but with one more parameter , copy the fixed n bits of a string to the target string . (including '\0') 

Implementation principle: perform a fixed number of copies according to the parameters passed in .

Call: Give the first addresses of two strings, and add an integer , as shown in the figure below

code:

 

//固定复制n位
//用const修饰源字符串,防止修改
char* my_strncpy(char* dest,const char* src,int num)
{
  //断言,不传空指针
  assert(dest&&src);
  //保存首地址
	char ret = dest;
	for (int i = 0; i < num; i++)
	{
		*dest++ = *src++;
	}
	return ret;
}
int main()
{
	char str1[20] = "666666666";
	char str2[20] = "bayuhao";
	printf("%s\n", str1);
	my_strncpy(str1, str2,7);
	printf("%s\n", str1);
	return 0;
}

(3) strncat ( ) function

Function: Similar to the strcat( ) function, but with one more parameter, only n characters are appended . 

Implementation principle: find the position of '\0', and then add n characters fixedly. (Note: If the number of characters in the source string is less than n, we should end the loop directly after adding '\0' to avoid out-of-bounds access )

Call: Give the first addresses of two strings, and add an integer , as shown in the figure below

code:

//固定追加n位
//用const修饰,避免修改源字符串
char* my_strncat(char* dest,const char* src,int num)
{
	//断言,不传空指针
	assert(dest&&src);
	//保存首地址
	char* ret = dest;
	while (*dest)
	{
		dest++;
	}
	for (int i = 0; i < num; i++)
	{
		//如果源字符串已经走到空,结束循环
		if (*src == '\0')
			break;
		*dest++ = *src++;
	}
	//给目标字符串尾加上'\0'
	*dest = '\0';
	return ret;
}
int main()
{
	char str1[20] = "hello ";
	char str2[20] = "world";
	printf("%s\n", str1);
	printf("%s\n", my_strncat(str1, str2, 4));
	return 0;
}

Three: several other functions

(1) strstr ( ) function

Function: Find a string in another string

Implementation principle:

[1] Pass in the first address of the two strings . (the string to be found and the parent string)

[2] Traverse the parent string from the beginning, if you find a character that is the same as the first character of the string to be searched , compare it backwards from this position , if the string to be searched reaches '\0' , it represents the parent character There is a string to be searched in the string , return the address of the first identical character, otherwise return NULL .

[3] If there is a difference in the traversal process, we need to reset the pointer to the parent string to the position next to the original traversal position , and reset the pointer to the string to be searched to the first address . Therefore, the pointer to the parent string should be recorded before traversing and comparing the two .

It doesn't matter if you don't understand, the illustration above:

Call: the first parameter is the first address of the parent string , and the second parameter is the first address of the string to be searched , as shown in the figure below

 

code:

 

//一个字符串里面找另一个字符串
//只是查找,为了避免修改,用const修饰
char* my_strstr(const char* str1,const char* str2)
{
	//断言,不传空指针
	assert(str1&&str2);
	char* s1 = str1;
	char* s2 = NULL;
	char* cp = s1;
	//如果为空,直接返回
	if(*str2=='\0')
		return (char*)str1;
	while (*cp)
	{
		s1 = cp;
		s2 = str2;
		//如果两者都没有走到空并且相同就继续
		while (*s1&&*s1 == *s2)
		{
			s1++;
			s2++;
			//如果待查找字符串走到空,返回
			if (*s2 == '\0')
				return (char*)cp;
		}
		cp++;
	}
	return  NULL;
}
int main()
{
	char str1[20] = "hebbitel";
	char str2[] = "bitel";
	char* ret = my_strstr(str1, str2);
	if (ret == NULL)
		printf("没找到\n");
	else
		printf("找到了\n");
	return 0;
}

(2) strerror ( ) function

Function: Pass in the error code and return the first address of the error message (string) .

Error code: In fact, every time we call a library function, an error code errno ( int type, declared in the header file errno.h, is a global variable ) will be generated.

transfer:

(3) strtok( ) function

Function: to split the string .

Implementation principle:

【1】In the first call, two initial addresses of strings are passed in, one of which is the initial address of the original string (such as "[email protected]")

, and the other is the first address of the split symbol string (such as "@.").

[2] The function will only find the position of '@' for the first time and modify it to '\0' . In order for us to continue to divide, the function will help us record the next position of the original @ (static variable) .

【3】In addition to the first call, in order to let the function know that we want to continue the segmentation , we need to change the first parameter passed in. If we pass in NULL, it tells the function that we want to continue the segmentation .

[4] If the function is completely divided, it will return a null pointer , otherwise it will return the first address of the part of the string that is divided this time.

transfer:

 

Guess you like

Origin blog.csdn.net/2301_76269963/article/details/130019473