当前位置:网站首页>C language --- string + memory function

C language --- string + memory function

2022-04-23 15:42:00 Tea rainbow

Catalog

One 、 Find the string length

1.strlen

Two 、 Unlimited length string function

1.strcpy

2.strcmp

3.strcat

3、 ... and 、 Introduction to string functions with limited length

1.strncpy

2.strncat

3.strncmp

Four 、 String search

1.strstr

2.strtok

5、 ... and 、 Error message report

strerror

6、 ... and 、 Character classification function :

7、 ... and 、 Character conversion

8、 ... and 、 Memory manipulation function

1.memcpy

2.memmove

3.memcmp

4.memset()

  Nine 、 Simulation Implementation strlen

The way 1:

The way 2:

The way 3:

Ten 、 Simulation Implementation strcpy

11、 ... and 、 Simulation Implementation strcat

Twelve 、 Simulation Implementation strstr

13、 ... and 、 Simulation Implementation memcpy


One 、 Find the string length

 1.strlen

size_t strlen ( const char * str );

The string has '\0' As an end sign ,strlen Function returns in a string '\0' The number of characters that appear before ( It doesn't contain '\0' ).

The string that the argument points to must be in '\0' end . Note that the return value of the function is size_t, It's unsigned ( Fallible )

The following code is the comparison of unsigned numbers   The answer should be >

#include <string.h>
#include <stdio.h>
int main()
{
	char arr[] = "abcdef";
	int len = strlen(arr);
	printf("%d\n", len);

	if ((int)strlen("abc") - (int)strlen("qwerty") > 0)
	{
		printf(">\n");
	}
	else
	{
		printf("<=\n");
	}
	return 0;
}

Two 、 Unlimited length string function

  1.strcpy

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

The source string must be in '\0' end . In the source string '\0' Copy to target space .

The target space has to be large enough , To ensure that the source string can be stored . The target space has to be variable .

int main()
{
	//const char* arr3 = "qwertyuiop";
	//arr1 Points to a constant string , Constants are immutable , So it can't be used for strcpy To copy 
	char arr1[] = "asdnsakhas";
	char arr2[] = "abcdef";
	strcpy(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}
#include <string.h>
#include <stdio.h>
#include <assert.h>
//strcpy The function returns the starting address of the target space 
//strcpy The return type of the function is set to achieve chained access 

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

int main()
{
	char arr1[20] = { 0 };
	const char* arr2 = "hello bit";

	printf("%s\n", my_strcpy(arr1, arr2));
	return 0;
}

 2.strcmp

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

The standard stipulates :

The first string is larger than the second string , Return greater than 0 The number of

The first string is equal to the second string , Then return to 0

The first string is less than the second string , Then return less than 0 The number of

int my_strcmp(const char* s1, const char* s2)
{
	assert(s1 && s2);
	while (*s1 == *s2)
	{
		if (*s1 == '\0')
		{
			return 0;// equal 
		}

		s1++;
		s2++;
	}
	// It's not equal 
	if (*s1 > *s2)
		return 1;
	else
		return -1;
}

int my_strcmp(const char* s1, const char* s2)
{
	assert(s1 && s2);
	while (*s1 == *s2)
	{
		if (*s1 == '\0')
		{
			return 0;// equal 
		}

		s1++;
		s2++;
	}
	// It's not equal 
	return *s1 - *s2;
}

int main()
{
	char arr1[] = "abcd";
	char arr2[] = "abdc";
	int ret = my_strcmp(arr1, arr2);
	if (ret >0)
	{
		printf(">\n");
	}
	else if (ret == 0)
	{
		printf("== \n");
	}
	else
	{
		printf("<\n");
	}
	printf("%d\n", ret);
	return 0;
}

3.strcat

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

The source string must be in '\0' end . The target space must be large enough , It can hold the contents of the source string .

The target space must be modifiable .

#include <string.h>
#include <stdio.h>
#include <assert.h>
char* my_strcat(char* dest, char* src)
{
	assert(dest && src);
	char* ret = dest;
	// Find... In the target space \0
	while (*dest)
	{
		dest++;
	}
	// Copy 
	while (*dest++ = *src++)
	{
		;
	}
    return ret;
}
int main()
{
	char arr1[20] = "hello";
	char arr2[] = " bit";
	printf("%s\n", my_strcat(arr1, arr2));	
	return 0;
}

The string appends itself , how ?

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

char* my_strcat(char* dest, char* src)
{
	assert(dest && src);
	char* ret = dest;
	// Find... In the target space \0
	while (*dest)
	{
		dest++;
	}
	// Copy 
	while (*dest++ = *src++)
	{
		;
	}
	return ret;
}

int main()
{
	char arr[20] = "bit";
	my_strcat(arr, arr);
	printf("%s\n", arr);

	return 0;
}

3、 ... and 、 Introduction to string functions with limited length

1.strncpy

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

Copy num Characters from the source string to the target space . If the length of the source string is less than num, After copying the source string , Add... After the target 0, until num individual .

int main()
{
	char arr1[] = "abcdef";
	char arr2[] = "qwe";
	strncpy(arr1, arr2, 5);
	printf("%s\n", arr1);
	return 0;
}

2.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;
}

  Output results :To be or not

int main()
{
	char arr1[20] = "abcdef\0XXXXXXXX";
	char arr2[] = "qwe";
	strncat(arr1, arr1, 5);
	printf("%s\n", arr1);
	return 0;
}

Output results :abcdefabcde      meet \0 It is considered to be the end of the string .

3.strncmp

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

Compare to the occurrence of a different character or the end of a string or num Compare all the characters .

/* 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;
}

Output results :

Looking for R2 astromech droids...
found R2D2
found R2A6

int main()
{
	char arr1[] = "abcdef";
	char arr2[] = "abcdq";
	int ret = strncmp(arr1, arr2, 5);	
	printf("%d\n", ret);
	return 0;
}

  Four 、 String search

1.strstr

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

/* 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;
} 

  The output is :This is a sample string

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

char* my_strstr(const char* str1, const char* str2)
{
	assert(str1 && str2);

	const char* s1 = str1;
	const char* s2 = str2;

	const char* cur = str1;
	while (*cur)
	{
		s1 = cur;
		s2 = str2;

		while (*s1 && *s2 && (*s1 == *s2))
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
			return (char*)cur;
		}
		cur++;
	}

	return NULL;// Can't find 
}

int main()
{
	char arr1[] = "abbbcdef";
	char arr2[] = "bbc";
	char* ret = my_strstr(arr1, arr2);
	if (NULL == ret)
	{
		printf(" No strings found \n");
	}
	else
	{
		printf("%s\n", ret);
	}
	return 0;
}

2.strtok

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

sep The parameter is a string , Defines the set of characters used as separators

The first parameter specifies a string , It contains 0 One or more by sep A character separated by one or more separators in a string remember .

strtok Function found str The next mark in , And use it \0 ending , Returns a pointer to the tag .( notes : strtok Function changes the string being manipulated , So it's using strtok The string segmented by function is usually the content of temporary copy And it can be modified .)

strtok The first argument of the function is not NULL , Function will find str The first mark in ,strtok The function will save it in the string Position in .

strtok The first argument to the function is NULL , The function will start at the same position in the string that is saved , Find the next target remember .

If there are no more tags in the string , Then return to NULL The pointer .

/* 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;
}

Output results :

Splitting string "- This, a sample string." into tokens:
This
a
sample
string 

#include <stdio.h>
int main()
{
     char *p = "zhangpengwei@bitedu.tech";
     const char* sep = ".@";
     char arr[30];
     char *str = NULL;
     strcpy(arr, p);// Make a copy of the data , Handle arr Contents of array 
     for(str=strtok(arr, sep); str != NULL; str=strtok(NULL, sep))
     {
         printf("%s\n", str);
     }
}

Output results :

zhangpengwei
bitedu
tech

5、 ... and 、 Error message report

strerror

char * strerror ( int errnum );

Return error code , The corresponding error message .

Global variables :errno( Error code )

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <stdlib.h>

int main()
{
	printf("%s\n", strerror(0));
	printf("%s\n", strerror(1));
	printf("%s\n", strerror(2));
	printf("%s\n", strerror(3));
	int* p = (int*)malloc(INT_MAX);// If you want to apply for memory in the heap     Need to add header file :#include <limits.h>
    //malloc If the function space application fails, a null pointer will be returned 

	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		perror("Malloc");
		return 1;
	}

	return 0;
}

Output results :

No error
Operation not permitted
No such file or directory
No such process
Not enough space
Malloc: Not enough space

6、 ... and 、 Character classification function :

function If his parameters meet the following conditions, it returns true
iscntrl Any control character
isspace Blank character : Space ‘ ’, Change the page ‘\f’, Line break '\n', enter ‘\r’, tabs '\t' Or vertical tabs '\v'
isdigit Decimal number 0~9
isxdigit Hexadecimal number , Include all decimal digits , Lowercase letters a~f, Capital A~F
islower Lowercase letters a~z
isupper Capital A~Z
isalpha Letter a~z or A~Z
isalnum Letters or numbers ,a~z,A~Z,0~9
ispunct Punctuation , Any graphic character that is not a number or letter ( Printable )
isgraph Any graphic character
isprint

Any printable character , Including graphic characters and white space characters

int main()
{
	char ch = 'A';
	putchar(toupper(ch));  //A
	putchar(tolower(ch));  //a
	return 0;
}

7、 ... and 、 Character conversion

int tolower ( int c );

int toupper ( int c );

/* isupper example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
      int i=0;
      char str[]="Test String.\n";
      char c;
      while (str[i])
      {
        c=str[i];
        if (isupper(c)) 
            c=tolower(c);
        putchar (c);
        i++;
      }
      return 0;
}

8、 ... and 、 Memory manipulation function

1.memcpy

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

function memcpy from source The position of begins to be copied back num Bytes of data to destination Memory location for .

This function is encountering '\0' It doesn't stop .

If source and destination There is any overlap , The results of replication are undefined .

int main()
{
	int arr1[] = { 1,2,3,4,5 };
	int arr2[] = { 1,2,3,4,0x11223305 };
	int ret = memcmp(arr1, arr2, 18);
	printf("%d\n", ret);
	return 0;
}
/* memcpy example */
#include <stdio.h>
#include <string.h>
struct 
{
      char name[40];
      int age;
} person, person_copy;
int main ()
{
      char myname[] = "Pierre de Fermat";
      /* using memcpy to copy string: */
      memcpy ( person.name, myname, strlen(myname)+1 );
      person.age = 46;
      /* using memcpy to copy structure: */
      memcpy ( &person_copy, &person, sizeof(person) );
      printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
      return 0;
}

 2.memmove

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

and memcpy The difference is that memmove The source and target memory blocks processed by the function can overlap .

If the source space and the target space overlap , You have to use memmove Function processing .

/* memmove example */
#include <stdio.h>
#include <string.h>
int main ()
{
  char str[] = "memmove can be very useful......";
  memmove (str+20,str+15,11);
  puts (str);
  return 0;
}

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>

void* my_memcpy(void* dest, const void* src, size_t count)
// The original data does not need to be changed , So add const modification src Enhance code robustness 
{
	assert(dest && src);  // Assertion    Can't be a null pointer 
	void* ret = dest;
	while (count--)
	{
		*(char*)dest = *(char*)src;// Cast is not permanent 
		dest = (char*)dest + 1;
		//dest yes void* Of type must first be cast to char* Add after type 1, Last void* Type can accept any type of pointer 
		src = (char*)src + 1;
	}

	return ret;
}

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

	if (dest < src)
	{
		// front -> after 
		while (count--)
		{
			*(char*)dest = *(char*)(src);
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		// after -> front 
		while (count--)
		{
			*((char*)dest+count) = *((char*)src + count);
		}
	}

	return ret;
}

// hold 1 2 3 4 5  copy to 3 4 5 6 7 The location of 
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[5] = { 0 };
	my_memcpy(arr2, arr1, 20);

	int arr3[10] = { 1,2,3,4,5,6,7,8,9,10 };
	               // 1 2 1 2 3 4 5 8 9 10
	memcpy(arr3+2, arr3, 20);

	//my_memmove(arr3+2, arr1, 20);// It can realize the copy of overlapping memory    Copy the front to the back 
	my_memmove(arr3, arr3+2, 20);// It can realize the copy of overlapping memory    Copy the back to the front 

	int i = 0;
	int sz = sizeof(arr3) / sizeof(arr3[0]);

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

	return 0;
}

 3.memcmp

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

Compare from ptr1 and ptr2 The pointer starts with num Bytes

The return value is as follows :

/* 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;
}

 4.memset()

int main()
{
	int arr[] = { 0x11111111,0x22222222,3,4,5 };
	memset(arr, 6, 20);//memset Initializes memory units in bytes 
	return 0;
}

 

  Nine 、 Simulation Implementation strlen

The way 1:

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

The way 2:

// Cannot create temporary variable counter 
int my_strlen(const char * str)
{
     if(*str == '\0')
         return 0;
     else
         return 1+my_strlen(str+1);
}

The way 3:

// The pointer - The way of the pointer 
int my_strlen(char *s)
{
     char *p = s;
     while(*p != ‘\0’ )
          p++;
     return p-s;
}

Ten 、 Simulation Implementation strcpy

//1. Parameter sequence 
//2. Function functions , Stop conditions 
//3.assert
//4.const Modify a pointer 
//5. Function return value 
//6. The title comes from 《 High-quality C/C++ Programming 》 The last part of the book is the test question 
char *my_strcpy(char *dest, const char*src)
{ 
     char *ret = dest;
     assert(dest != NULL);
     assert(src != NULL); 
     while((*dest++ = *src++))
     {
         ;
     }
     return ret;
}

11、 ... and 、 Simulation Implementation strcat

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

Twelve 、 Simulation Implementation strstr

char *  strstr (const char * str1, const char * str2)
{
        char *cp = (char *) str1;
        char *s1, *s2;
        if ( !*str2 )
            return((char *)str1);
        while (*cp)
        {
             s1 = cp;
             s2 = (char *) str2;
             while ( *s1 && *s2 && !(*s1-*s2) )
                  s1++, s2++;
             if (!*s2)
                  return(cp);
             cp++;
        }
        return(NULL);
}

13、 ... and 、 Simulation Implementation memcpy

void * memcpy ( void * dst, const void * src, size_t count)
{
     void * ret = dst;
     assert(dst);
     assert(src);
     /*
      * copy from lower addresses to higher addresses
      */
     while (count--) 
     {
          *(char *)dst = *(char *)src;
          dst = (char *)dst + 1;             
          src = (char *)src + 1;
     }
     return(ret);
}

版权声明
本文为[Tea rainbow]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231532440056.html