Hello C language - string and memory functions

introduction

Characters and strings are processed frequently in C language , but C language itself does not have a string type. Strings are usually placed in constant strings or character arrays . String constants are suitable for string functions that do not modify them .

Function introduction

There are many string functions, and their functions are different. Next, I will introduce them to you one by one.

1.strlen

Introduction to strlen function

size_t strlen ( const char * str );

size_t is the return type of the strlen function. The purpose of the strlen function is to find the length of the string, and size_t is used to receive the returned length.

Notice:

  1. The string has '\0' as the end mark, and the strlen function returns the number of characters that appear before '\0' in the string (excluding '\0').
  2. The string pointed to by the parameter must end with '\0'.
  3. Note that the return value of the function is size_t, which is unsigned (error-prone)

Autonomous implementation of strlen function

#include<stdio.h>
#include<assert.h>
size_t my_strlen(const char* str)
{
	int count = 0;

	assert(str != NULL);

	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}

int main()
{
	char arr[10] = "abcdef";

	int len = my_strlen(arr);

	printf("%d", len);

	return 0;
}


2. strcpy

Introduction to strlen function

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

  1. The source string must end with '\0'.
  2. '\0' in the source string will be copied to the target space.
  3. The target space must be large enough to accommodate the source string.
  4. The target space must be variable

Independent implementation of strcpy function

//strcpy函数 返回的是目标字符串的原地址,所以需要在dest++还没开始时,单独定义出来一个原
//地址,用于最后返回
char* my_strcpy(char* dest, const char* src)
{
	/*assert(dest != NULL);
	assert(src != NULL);*/
	也可以这样断言
	assert(dest && src);

	char* ret = dest;

	while (*dest++ = *src++)
	{
		;
	}
	return ret;
}

int main()
{
	char arr1[10] = { 0 };

	char* arr2 = "work hard";

	my_strcpy(arr1, arr2);

	printf("%s", arr1);
	return 0;
}

strncpy

char * strncpy ( char * destination, const char * source, size_t num );

  1. Copy num characters from the source string to the destination space.
  2. 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

3. strcat

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

Introduction to strcat function

  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.
  4. How about appending the string to itself?

Independent implementation of strcat function

//strcat函数 
char* my_strcat(char* dest, const char* src)
{
	/*assert(dest != NULL);
	assert(src != NULL);*/
	//也可以这样断言
	assert(dest && src);

	char* ret = dest;

	while (*dest)
	{
		dest++;
	}

	while (*dest++ = *src++)
	{
		;
	}

	return ret;
}

int main()
{
	char arr1[20] = "work";

	char arr2[] = " hard";

	printf("%s", my_strcat(arr1, arr2));

	return 0;
}

strncat

char * strncat ( char * destination, const char * source, size_t num );

/* strncat example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[20];
char str2[20];
strcpy (str1,"To be ");
strcpy (str2,"or not to be");
strncat (str1, str2, 6);
puts (str1);
return 0;
}
int strncmp ( const char * str1, const char * str2, size_t num );

4. strcmp

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

Introduction to strcmp function

standard regulation:

  1. If the first string is greater than the second string, a number greater than 0 is returned.
  2. If the first string is equal to the second string, 0 is returned
  3. If the first string is less than the second string, a number less than 0 is returned.

Independent implementation of strcmp function

int my_strcmp(char* str1,char* str2)
{
	assert(str1 && str2);

	while (*str1 == *str2)
	{
		if (*str1 = '\0')
		{
			return 0;
		}

		str1++;
		str2++;
	}
	if (*str1 > *str2)
	{
		return 1;
	}

	else
		return -1;
}

int main()
{
	char arr1[10] = "abc";
	char arr2[20] = "abcd";

	int ret = my_strcmp(arr1, arr2);

	if (ret == 0)
	{
		printf("==");
	}

	else if (ret > 0)
	{
		printf(">");
	}

	else
		printf("<");

	return 0;
}

strncmp

int strncmp ( const char * str1, const char * str2, size_t num );

Compare until another character is different or a string ends or all num characters are compared.

/* strncmp example */
#include <stdio.h>
#include <string.h>
int main()
{
	char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
	int n;
	puts("Looking for R2 astromech droids...");
	for (n = 0; n < 3; n++)
		if (strncmp(str[n], "R2xx", 2) == 0)
		{
			printf("found %s\n", str[n]);
		}
	return 0;
}


5. strstr

char * strstr ( const char *, const char * );

Introduction to strstr function

Find a string within another string

/* strstr example */
#include <stdio.h>
#include <string.h>
int main()
{
	char str[] = "This is a simple string";
	char* pch;
	pch = strstr(str, "simple");
	strncpy(pch, "sample", 6);
	puts(str);
	return 0;
}

Independent implementation of strstr function

六、strtok

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

Introduction to strtok function

  1. The sep parameter is a string that defines the set of characters used as separators.
  2. The first parameter specifies a string containing zero or more tokens separated by one or more delimiters in the sep string.
  3. The strtok function finds the next token in str, terminates it with \0, and returns a pointer to this token. (Note: The strtok function will change the manipulated string, so the string split using the strtok function is generally a temporary copy and can be modified.)
  4. The first parameter of the strtok function is not NULL, the function will find the first token in str, and the strtok function will save its position in the string.
  5. The first parameter of the strtok function is NULL, and the function will start at the saved position in the same string and find the next token.
  6. If there are no more tokens in the string, a NULL pointer is returned.
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
 char str[] ="- This, a sample string.";
 char * pch;
 printf ("Splitting string \"%s\" into tokens:\n",str);
 pch = strtok (str," ,.-");
 while (pch != NULL)
{
  printf ("%s\n",pch);
  pch = strtok (NULL, " ,.-");
}
 return 0;
}

7.strerorr

char * strerror ( int errnum );

Introduction to strorrr function

Returns the error code and corresponding error information.

/* strerror example : error list */
#include <stdio.h>
#include <string.h>
#include <errno.h>//必须包含的头文件
int main()
{
	FILE* pFile;
	pFile = fopen("unexist.ent", "r");
	if (pFile == NULL)
		printf("Error opening file unexist.ent: %s\n", strerror(errno));
	//errno: Last error number
	return 0;
}

8. memcpy

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

Introduction to memcpy function

  1. The function memcpy copies num bytes of data starting from the source location to the destination memory location.
  2. This function does not stop when it encounters '\0'.
  3. If there is any overlap between source and destination, the results of copying are undefined.

Independent implementation of memcpy function

void* my_memcpy(void* dest, const void* src, size_t count)
{
	assert(dest && src);//断言

	void* ret = dest;//返回的是void*类型 但是dest不会改变

	while (count--)
	{
		*(char*)dest = *(char*)src;//强制类型转换为char类型
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}

	return ret;
}
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };

	int arr2[5] = { 0 };

	my_memcpy(arr2, arr1,20);

	return 0;
}

9. memmove

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

Introduction to memmove function

  1. The difference with memcpy is that the source memory block and target memory block processed by the memmove function can overlap.
  2. If the source space and target space overlap, you have to use the memmove function.

Autonomous implementation of memmove function

void my_memmove(void* dest, const void* src, size_t count)
{
	assert(dest && src);

	void* ret = dest;
	if (dest < src)
	{
		//前 -> 后
		while (count--)
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}

	else
	{
		//后 -> 前
		while (count--)
		{
			*((char*)dest + count) = *((char*)src + count);
		}
	}


	//if (dest > src && dest < (char*)src + 20)
	//{
	//	//后 -> 前
	//}
	//else
	//{
	//	//前 -> 后
	//}

	return ret;
}
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };

	int arr2[5] = { 0 };

	my_memmove(arr1 + 2, arr1, 20);

	//my_memmove(arr1, arr1 + 2, 20);

	int sz = sizeof(arr1) / sizeof(arr1[0]);

	for (int i = 0;i < sz;i++)
	{
		printf("%d ", arr1[i]);
	}

	return 0;
}

10.mencmp

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

Introduction to memmove function

Compare num bytes starting from the ptr1 and ptr2 pointers

/* memcmp example */
#include <stdio.h>
#include <string.h>
int main()
{
	char buffer1[] = "DWgaOtP12df0";
	char buffer2[] = "DWGAOTP12DF0";
	int n;
	n = memcmp(buffer1, buffer2, sizeof(buffer1));
	if (n > 0) printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
	else if (n < 0) printf("'%s' is less than '%s'.\n", buffer1, buffer2);
	else printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
	return 0;
}

Guess you like

Origin blog.csdn.net/cdtu_mid/article/details/131858680