The use and analysis of string operation function and memory function in C language

Table of contents

1. String manipulation functions

1. strlen function

1.1 Function and prototype of strlen function

1.2 Three ways to customize the strlen function

1.2.1 Realized by means of counter

1.2.2 Implementation using recursion

1.2.3 The method of subtracting pointers from pointers

2. strcpy function

2.1 strcpy function prototype and function

2.2 Custom implementation of strcpy function

3. strcat function

3.1 Prototype and function of strcat function

3.2 Custom implementation of strcat function

4. strcmp function

4.1 strcmp function prototype and function

4.2 Custom implementation of strcmp function

5. strncpy function

6. strncat function

7. strncmp function

8. strstr function

8.1 Function prototype and function

8.2 Custom implementation of strstr function

9. strtok function

10. strerror function

11. Character classification function

12. Character conversion function

2. Memory function

1. memcpy function

1.1 Function function and prototype

1.2 Custom implementation of memcpy function

2. memmove function

3. memcmp function

4. memset function


1. String manipulation functions

1. strlen function

1.1 Function and prototype of strlen function

The strlen function calculates the length of the string until '\0' is found, where strlen returns an unsigned int, that is, an unsigned number, for example:

if(strlen("abc")-strlen("abcdef"))>0
{
    printf("haha");
}
else
    printf("hehe");   //结果为haha,两个无符号数相减,得到的也是无符号数

1.2 Three ways to customize the strlen function

1.2.1 Realized by means of counter

int my_strlen(char* str)
{
	int count = 0;
	while (*str++)
	{
		count++;
	}
	return count;
}

1.2.2 Implementation using recursion

int my_strlen(char* str)
{
	if (*str=='\0')return 0;
	return 1 + my_strlen(str + 1);
}

1.2.3 The method of subtracting pointers from pointers

The pointer minus the pointer can get the number of characters in the two pointers, the code is as follows:

int my_strlen(char* str)
{
	char* base = str;
	while (*str != '\0')
	{
		str++;
	}
	return str - base;
}

2. strcpy function

2.1 strcpy function prototype and function

The prototype of the strcpy function is:

char* strcpy(char* destination,const char* source)

Its function is to realize the copying of strings, and '\0' will also be copied during the copying process, for example:

int main()
{
    char arr1[]="abcdefghi";
    char arr2[]="bit";
    strcpy(arr1,arr2);
    //拷贝的过程中, '\0'也拷贝过去了;
    //此时arr1内容变成bit;
}

2.2 Custom implementation of strcpy function

Regular writing:

my_strcpy(char* dest,char* src)
{
    assert(dest!=NULL);
    assert(src!=NULL);
    while(*src!='\0')
    {
    *dest=*src; //拷贝字符;
    dest++;
    src++;
    }
    *dest=*src;  //将'/0'拷贝过去;
}  //这种写法不够精简

Shorthand:

char* my_strcpy(char* dest,const char* src)
{
	char* ret = dest;
	assert(*dest && *src);
	while (*dest++ = *src++);
	return ret;
}

Note: The target space must be large enough

3. strcat function

3.1 Prototype and function of strcat function

Function: Append a string, '\0' will also be appended together (cannot be used to append for yourself)

Function prototype:

char* strcat(char* destination, const char* source)

Example:

int main()
{
    char arr1[]="hello";
    char arr2[]="world";
    strcat(arr1,arr2);//得到helloworld,但是会空间不够,造成越界访问;
}

3.2 Custom implementation of strcat function

char* my_strcat(char* dest, char* src)
{
	assert(dest && src);  //assert断言防止对空指针进行操作
	char* ret = dest;
	while (*dest != '\0')  //找到目标的'\0'
	{
		dest++;
	}
	while (*dest++ = *src++);  //追加
	return ret;
}

4. strcmp function

4.1 strcmp function prototype and function

Function prototype:

int strcmp(const char*str1,const char* str2)

Function:

If the first string is greater than the second string, return a number greater than 0;

Returns 0 if the first string is equal to the second string;

If the first string is less than the second string, return a number less than 0;

Comparison rules: compare the ASCII code value of the first character, if they are equal, compare the ASCII code value of the next character, if greater, return 1, if less than, return -1;

In vs, greater than returns 1, less than returns -1; but in other compilers, greater than or less than will return the difference in ASCII code, >0 or <0;

4.2 Custom implementation of strcmp function

int my_strcmp(const char* str1,const char* str2)
{
	while (*str1 == *str2)
	{
		if (*str1 == '\0')
		{
			return 0;
		}
		str1++;
		str2++;
	}
	if (*str1 > *str2)
	{
		return 1;
	}
	else if(*str1<*str2)
		return -1;
}

5. strncpy function

Function description:

Because there will be insufficient space when using strcpy, or the string you want to copy does not meet your needs, so the strncpy function appears, and its function prototype is:

char* strcpy(char* destination,const char* source,unsigned int num)

Where num is the number of characters to be copied.

Example:

int main()
{
    char arr1[5]="abc";
    char arr2[]="hello bit";
    strncpy(arr1,arr2,4);  //目的,来源,个数;  结果为hell
    //不会拷贝'\0'过去;
    //若拷贝的字符数量大于arr2,则多的部分补成'\0';
}

6. strncat function

Function description:

Here is the same as strncpy, it also adds the function of specifying the number of characters, or appends a string after '\0'

Function prototype:

char* strcat(char* destination, const char* source,unsigned int num)

Example:

int main()
{
    char arr1[30]="abc";
    char arr2[]="hello";
    strncat(arr1,arr2,4);  //目的,来源,个数;
    //追加时会带一个'\0'过去
    //个数比arr2长时,就直接将arr2一整个追加过去,但会补个'\0';
}

7. strncmp function

Function function:

Similarly, the strncmp function is an improvement of the strcmp function, that is, the number of characters to be compared can be specified

Function prototype:

int strncmp(const char* str1,const char* str2,unsigned int count)

Example:

int main()
{
  const  char* p1="abcdef";
  const  char* p2="abcqwer";
    int ret=strncmp(p1,p2,3);  //ret=0;
    
}

8. strstr function

8.1 Function prototype and function

The strstr function is to find the substring function, and its function prototype is:

strstr(const char* str1,const char* str2)

Example:

int main()
{
    char* p1="abcdefghi";
    char* p2="def";
    char* ret=strstr(p1,p2); //在p1中找p2是否存在,如果存在,返回p2的首元素地址;不存在则返回NULL空指针;
    if(ret==NULL)
    {
        printf("找不到子串");
    }
    else
        printf("%s\n",ret);  //返回值为defghi;
    return 0;
}

8.2 Custom implementation of strstr function

char* my_strstr(char* p1, char* p2)
{
	char* cur = p1;
	char* s1 = p1;
	char* s2 = p2;
	while (*cur)
	{
		s1 = cur;
		s2 = p2;
		while ((*s1 != '\0') && (*s2 != '\0') && *s1 == *s2)
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
			return cur;  //找到了
		}
		cur++;
	}
	return NULL;  //未找到
}

9. strtok function

Function function: The strtok function is used to obtain a certain segment in a string

For example, like 192.168.31.121, where . is the separator, if you want to get a certain segment, you can use the strtok function

The separators of mailboxes like [email protected] are @ and .

Function prototype:

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

Example of function usage:

char arr[]="[email protected]";
char* p="@.";
strtok(arr,p);  //第二次使用时,第一个参数传空指针即可;
strtok(NULL,p);  //后面使用第一个都是传空指针

The strtok function finds the mark symbol in str and changes it to '\0', returns a pointer to the mark, and then saves the position of the mark, and finds the second mark symbol from the position of the mark for the second time , or NULL if no more tokens exist;

The strtok function will copy a copy of the data in advance, and then cut all the copied data, the original data is fine.

char* ret=NULL;
for(ret=strtok(arr,p);ret!=NULL;ret=strtok(NULL,p));
{
    printf("%s\n",ret);  //一次就能打印完,秒就秒在for循环只初始化一次,同时strtok函数中arr也只调用一次;
}

10. strerror function

Function function: error reporting function

Function prototype:

char *strerror(int errnum);

Example:

int main()
{
    //strerror函数即把相应数字翻译为错误信息
    //0,1,2,3····是错误码,每一个错误码对应一个错误信息,
    char* str=strerror(0);
    printf("%s\n",str);//打印结果为 No error;
    char* str=strerror(1);
    printf("%s\n",str);  //结果为 operation not permitted
     char* str=strerror(2);
    printf("%s\n",str);  //结果为No such file or directory
    
    
    char* str=strerror(errno)  //得引头文件 errno.h
        //errno是一个全局变量,当C语言执行过程中出现错误,会把对应的错误码返回给errno;
    return 0;  
}

11. Character classification function

 Example:

int main()
{
    char ch="w";
    int ret=islower(ch);// 头文件为ctype.h
    printf("%d",ret);  //如果是小写字母,返回非0数字,否则返回0;(非零数字未必是1);
    return 0;
}

12. Character conversion function

Function prototype:

int tolower(int c);   //大写转换为小写
int toupper(int c);   //小写转换为大写

Example:

int main()
{
    char ch1=tolowr('Q');
    putchar(ch1);  //结果为小写字母q;
    char ch2=toupper('q');
    putchar(chr2); //结果为大写字母Q;
}

Use: (conversion of uppercase and lowercase characters in the array)

int main()
{
    char arr[]="I Am A Student";
    int i=0;
    while(arr[i])
    {
        if(isupper(arr[i]))
        {
            arr[i]=tolower(arr[i]);
        }
        i++; 
    }
    printf("%s\n",arr);  //得到结果全为小写;
}

2. Memory function

The header file is <memory.h>

Functions such as strcpy and strcat operate on strings, but integer arrays, floating-point arrays, and structure arrays cannot.

1. memcpy function

1.1 Function function and prototype

Function function: memory copy, any data type can be copied

Function prototype:

void* memecpy(void* destination,const void* source,size_t num);
//void*可以接受任意类型的地址,

The function memcpy copies num bytes of data from the position of source to the memory position of destination;

·Will not stop when encountering '\0';

Example:

int main() //整形数组中进行memcpy的操作
{
    int arr1[]={1,2,3,4,5};
    int arr2[5]={0};
    memcpy(arr2,arr1,sizeof(arr1));// 此时arr2的数就变成了1,2,3,4,5;
}
struct s  
{
    char name[20];
    int age;
};
int main()  //拷贝结构体
{
    struct s arr3[]={
   
   {"zhangsan",20},{"lisi",30}};
    struct s arr4[]={0};
    memcpy(arr4,arr3,sizeof(arr3));
}

1.2 Custom implementation of memcpy function

void* my_memcpy(void* dest, const void* src, size_t num)
{
	void* ret = dest;
	while (num--)
	{
		*(char*)dest = *(char*)src;
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}
	return ret;
}

2. memmove function

In the case of using the memcpy function, if we specify the parameters as (arr2, arr, 20) when using it, there will be memory overlap, making it impossible to store normally, and memove can solve this problem.

Function prototype:

void* memecpy(void* destination,const void* source,size_t num);

Custom implementation of memmove function

void* my_memmove(void* dest, const void* src, size_t num)
{
	void* ret = dest;
	if (dest < src)
	{
		while (num--)
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		while (num--)
		{
			*((char*)dest + num) = *((char*)src + num);
		}
	}
	return ret;
}

3. memcmp function

Function prototype:

int memcmp(const void* ptr1,const void* ptr2,size_t num);

Similar to strcmp, it returns 0 when equal, 1 if ptr1>ptr2, and -1 if ptr1<ptr2

Example:

#include <stdio.h>
#include <memory>.h
int main()
{
    int arr1[] = { 1,2,3,4,5 };
    int arr2[] = { 1,2,5,4,3 };
    int ret = memcmp(arr1, arr2, 9);  //若相等返回0,若arr1<arr2,则返回-1;若arr1>arr2的返回1;
    printf("%d\n", ret);  //这里返回的是-1
    return 0;
}

4. memset function

Function prototype and function:

The memset function is a memory setting function

Its function prototype is:

void* memset(void* dest,int c,size_t count);

It should be noted here that memset modifies the number of bytes, that is, modifies byte by byte, and you need to be careful when assigning integer arrays.

Examples are as follows:

int main()
{
     char arr[10]="";
    memset(arr,'#',10);// 此时arr中的10个元素全为#;
}
int main()
{
    int arr[10]={0};
    memset(arr,1,10);  //注意,第三个改的是字节数,不是元素个数即每次一个一个字节的改
    //01 01 01 01 01 01 01 01 01 00 00 ···
}

Guess you like

Origin blog.csdn.net/yss233333/article/details/123695483