Hand to hand teaching: introduction of character function and Its Simulation Implementation

Keywords: C

1. Find string length function

Usage and Simulation Implementation of strlen

strlen() function: this function calculates the number of characters in the string from the first character until it encounters an empty character, that is' \ 0 ', and then returns the length of the calculated number of characters, including' \ 0 '.

Next, let's use MSDN to see the actual application method of strlen function:

Note: from the above, we can know the return type of strlen function: size_t (unsigned integer)

Specific usage: next, let's try to implement a simple strlen function:
Header file: #include "string.h"

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

int  main()
{
	char arr[] = "abccd";
	printf("%d", strlen(arr));
	return 0;
}


After knowing the usage and principle of strlen function, we also try to make a function with the same purpose as strlen function.
The simulation is realized as follows:

#include<stdio.h>
#include<string.h>
#include<assert.h>
size_t my_str(char* arr)
{
	int count = 0;
	assert(arr != NULL);
	while (*arr++)
	{
		count++;
	}
	return count;
}

int main()
{
	char arr[] = { "aabcdefwcng" };
	
	int num = my_str(arr);
	printf("%d\n", num);
	return 0;
}

2. String function with unlimited length

strcpy


Specific usage:
Header file: #include "string.h"

#include<string.h>
#pragma warning(disable:4996) 
#include <stdio.h>
int  main()
{
	char a[20], c[] = "I am a student!";
	strcpy(a, c);
	printf(" c=%s\n", c);
	printf(" a=%s\n", a);
	return 0;
}


After knowing the usage and principle of strcpy function, we also try to make a function with the same purpose as strcpy function.
The simulation is realized as follows:

#include<stdio.h>
#include<assert.h>
void my_strcpy(char* dest, const char* src)

{
	assert(src != NULL);
	assert(dest != NULL);
	
	while (*dest++ = *src++)
	{
		;
	}
}
int main()
{

	char arr1[] = "abcdef";
	char arr2[10] = "xxxxxxxxxxx";
     my_strcpy(arr2, arr1);
	printf("%s\n", arr2);

	return 0;
}


be careful:
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.
4. The target space must be variable

strcat

For the strcat function, it actually adds another string after the previous string. When using it, note that the added space should be large enough to prevent overflow after appending;

From MSDN, we can see that the use methods of strcat and strcpy are very similar. They both have the same parameter layout and return type
Specific usage:
Header file: #include "string.h"

#include<stdio.h>
#include<string.h>
#pragma warning(disable:4996) 

int main()
{

	char a[30] = "zhoumin is ";
    char b[] = "a good girl!";

	printf("%s",strcat(a, b));
	return 0;
}
	


After knowing the usage and principle of strcat function, we also try to make a function with the same purpose as strcat function.
The simulation is realized as follows:

#include <stdio.h>
#include <assert.h>

char* MyStrcat(char* dest, const char* src)
{
	char* ret = dest;
	assert(dest != NULL);
	assert(src != NULL);
	while (*dest)
	{
		dest++;
	}
	while ((*dest++ = *src++))
	{
		;
	}
	return ret;
}

int main()
{
	char str[20] = "Hello";
	printf("%s\n", MyStrcat(str, " my girl"));
	return 0;
}


be careful:
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.

strcmp

Function: compare a and b strings. strcmp function compares two strings according to ASCII code. Subtract the first character of b string from the first character of a string. If the first character is equal, compare the second character. If a and b are completely equal, return 0 and continue to compare the size of the following characters; If a is greater than b, a value greater than 0 will be returned; If a is less than b, it also returns a value less than 0

Specific usage:
Header file: #include "string.h"

#include<stdio.h>
#include<string.h>
int main() {
	const char* str1 = "abcd";
	const char* str2 = "abdc";
	int xx = strcmp(str1, str2);
	printf("%d", xx);
	return 0;
}


After knowing the usage and principle of strcmp function, we also try to make a function with the same purpose as strcmp function.
The simulation is realized as follows:

#include <stdio.h>
#include<assert.h>
#include<Windows.h>
int my_strcmp(char* str1, char* str2)
{
	assert(str1);
	assert(str2);
	while (*str1 == *str2)
	{
		if (*str1 == '\0' || (*str2 = '\0'))
			return 0;
		str1++;
		str2++;
	}
	return *str1 - *str2;
}

int main()
{
	char str[32] = "bcdefg";
	char buf[32] = "bcdefg";
	char erc[32] = "abcdeg";
	char std[32] = "cdafgh";
	printf("%d\n", my_strcmp(str, buf));
	printf("%d\n", my_strcmp(str, erc));
	printf("%d\n", my_strcmp(str, std));
	system("pause");
	return 0;
}

3. Briefly introduce string functions with limited length

All the string functions introduced above are string functions with unlimited length, but in fact, it is much safer to use string functions with limited length than unrestricted ones. If you can, I still hope you can choose string functions with limited length more rigorously.
In simple and popular terms: in fact, the string function with limited length is to add an n (after str) in the middle of each function, which limits the specific number of (cpy) (cat) (cmp) when using the function, and correspondingly adds a parameter (size_t type) when using the function

strncpy

Function: copy num characters from the source string to the target space
Header file: #include "string.h"

Specific usage:

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>



int main()
{
	char str1[256] = { 0 };
	char str2[] = "abcdefgh";
	strncpy(str1, str2, 7);
	printf("%s\n", str1);

	system("pause");
	return 0;
}

strncat

Function: strncat() will copy n characters from the beginning of src string to the end of DeST string. Dest should have enough space to accommodate 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. Strncat() will overwrite '\ 0' at the end of DeST string, and then append '\ 0' after character addition.
Header file: #include "string.h"

Specific usage:

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>

#include<assert.h>



int main()
{
	char str1[256] = "abcdefg";
	char str2[] = "higklmn";
	strncat(str1, str2, 5);
	printf("%s\n", str1);

	
	return 0;
}

strncmp

Function: the function is to compare the first n bytes of arr1 and arr2. If the first n characters of arr1 and arr2 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.
be careful:
arr1 -- the first string to compare
arr2 -- the second string to compare.
n -- maximum number of characters to compare.
Return value:
If the return value < 0, it means that arr1 is less than arr2.
If the return value > 0, it means that arr2 is less than arr1.
If the return value = 0, it means that arr1 is equal to arr2.

Specific usage:

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<assert.h>
int main()
{
	char arr1[] = "abcd";
	char arr2[] = "abcefgh";
	int a=strncmp(arr1, arr2, 4);
	printf("%d", a);

	return 0;
}

4. String lookup function

strstr

Many people may have ignored this function, which I think is very practical. The strstr(str1,str2) function is one of the string processing functions, which is located in the header file "string.h". It is very helpful to deal with some problems of string.
Definition: the strstr(str1,str2) function is used to determine whether the string str2 is a substring of str1. If yes, the function returns the address where str2 first appears in str1; Otherwise, NULL is returned.

Let me give you an example:
char arr1[]="abcdef";
char arr2[]="cd";
Then the function will return the address of c, starting from the first address' \ 0 'and ending at the end of printing
cdef will be printed and NULL pointer will be returned if not found

Specific usage:

#include<stdio.h>
#include<assert.h>
#include<string.h>
int main() {
	char arr1[] = "hello world ";
	char arr2[] = "llo w";
	char* g = strstr(arr1, arr2);//function call
	printf("%s", g);
	return 0;
}

strtok

definition
Decomposes a string into a set of strings. S is the character to be decomposed and delim is the separator character (if a string is passed in, each character in the passed in string is a separator). When calling for the first time, s points to the string to be decomposed. After calling again, set s to NULL. In the header file #include < string. H >.

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

The sep parameter is a string that defines the set of characters used as delimiters
The first parameter specifies a string that contains 0 or more tags separated by one or more separators in the sep string
Remember.
The strtok function finds the next tag in str, ends it with \ 0, and returns a pointer to this tag. (Note:
The strtok function will change the string to be manipulated, so the string segmented by the strtok function is generally a temporary copy
And can be modified.)
The first parameter of the strtok function is not NULL. The function will find the first tag in str, and the strtok function will save it in the string
Position in the.
The first parameter of strtok function is NULL. The function will start at the position saved in the same string to find the next index
Remember.
If there are no more tags in the string, a NULL pointer is returned.
Specific usage:

#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996) 

int main(void) {
    char str[12] = "hello,world\0";
    char* token = strtok(str, ",");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }

    return 0;
}

5. Error message reporting function

strerror

Function: obtain the description string of the error through the label of the standard error, and convert the simple error label into a string description. First, the system will assign errno according to the execution error of the previous statement. On this point, we first understand two points. First, errn is a system variable that does not need to be assigned or declared. Second, errn is a variable of type int, and its value corresponds to a specific error type
Then, with regard to streerror () itself, it can be understood as follows. As the name suggests, streerror = string + error is to translate the errno value into a string statement describing the error type!

Parameters:
errnum: the latest error label.
Return value:
Pointer to the error message.

I'll introduce you all here
Finally completed this ten thousand word blog, the process is still very tired, but the feeling of reviewing the old knowledge is still very good, and gained a lot of new understanding.

Posted by Megienos on Sun, 03 Oct 2021 16:37:51 -0700