C language advanced character functions and string functions

This article mainly focuses on the use and precautions of library functions for processing characters and strings.

~Find the length of a string
strlen
~String function with unlimited length
strcpy strtok< /span>~Memory operation function memcmp memset memmove memcpy~Character operation strerror~Error message report strstr~String search strncmp strncat strncpy~Introduction to string functions with limited length strcmp
strcat















Table of contents

1 Introduction

2. Function introduction

2.1 strlen 

2.2 strcpy

2.3 cracked

2.4 strcmp

2.5 strncpy

2.6 strncat

2.7 strncmp

2.8 strstr

2.9 strtok 

2.10 string error 

2.11 memcpy

2.12 memmove

2.13 memcmp


1 Introduction

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

 

2. Function introduction

2.1 strlen 

size_t strlen ( const char * str ); 

 ! String already '\0' as the end mark, strlen The function returns the number of characters that appear before '\0' in the string (not including
Contains'\0' )

 ! The string pointed to by the parameter must end with '\0'.
 ! Note that the return value of the function is size_t, which is unsigned ( Error-prone )
 ! Learn the simulation implementation of strlen function

Why is the function return value size_t error-prone? Please look at the following code:

#include <stdio.h>
#include <string.h>
int main()
{
    const char*str1 = "abcdef";
    const char*str2 = "bbb";
    if(strlen(str2)-strlen(str1)>0)
    {
        printf("str2>str1\n");
    }
    else
    {
        printf("srt1>str2\n");
    }
        return 0;
}

 The code results are as follows:

Is there anyone here who thinks thatstr1 > str2 is right? Here we need to mention again the return value of strlen functionsize_t, which is unsigned integer a>, when two unsigned integer types are subtracted, the result will also be an unsigned integer type, so the result obtained from 3 - 6 is regarded by the system as an unsigned number, so the result obtained is 3 - 6 > 0

2.2 strcpy

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

  Copies the C string pointed by source into the array pointed by destination, including the
  terminating null character (and stopping at that point).

Copies the C string pointed to by source into the array pointed to by destination, including the terminating null character (and stopping at that point).

The blogger summarized it with two words: "replacement". The source code will replace the data of the target code. The code is as follows:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	strcpy(arr1, arr2);
	printf("%s" , arr1);
	return 0;
}

Since the '\0' of the source string will also be copied, when you print the target string, cccc replaces abcd, but '\0' is also copied in, so the printing stops. Here, the subsequent ef g is still in the target string.

The source string must end with '\0'.
will copy '\0' in the source string to the target space.
The target space must be large enough to ensure that the source string can be stored.
The target space must be variable.
Learn to simulate implementation

2.3 strcat

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

 Appends a copy of the source string to the destination string. The terminating null character
in destination is overwritten by the first character of source, and a null-character is included
at the end of the new string formed by the concatenation of both in destination.

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character from the source, and contains a null character at the end of the new string formed by the concatenation of the two in destination.

The blogger summarized it in two words: "tail chasing". The source string will be added to the end of the target string. The code is as follows:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	strcat(arr1, arr2);
	printf("%s" , arr1);
	return 0;
}

The source string must end with '\0'.
The target space must be large enough to accommodate the content of the source string.
The target space must be modifiable.
How about appending the string to itself?

As shown in the picture, you can add it yourself, but you must ensure that the target space is large enough! ! !

2.4 strcmp

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

This function starts comparing the first character of each string. If they are equal to each
other, it continues with the following pairs until the characters differ or until a terminating
null-character is reached.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters are different or the terminating null character is reached.

The blogger summarized the "size comparison". This function is used to compare the size of the corresponding positions of two strings( ASCII code value), the code is as follows:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	int ret = strcmp(arr1, arr2);
	printf("%d" , ret);
	return 0;
}

Standard regulations:
! The first string is greater than the second string, then a number greater than 0 is returned
! The first string is equal to the second string, then 0
is returned! The first string is less than the second string, then a number less than 0 is returned

2.5 strncpy

char * strncpy ( char * destination, const char * source, size_t num );
 Copies the first num characters of source to destination. If the end of the source C string
(which is signaled by a null-character) is found before num characters have been copied,
destination is padded with zeros until a total of num characters have been written to it.

Copies the first num characters of the source code to the target. If the end of the source C string (signaled by a null character) is found before num characters have been copied, the destination is padded with zeros until a total of num characters have been written.

Do you think this function looks familiar? Is it very similar to the above 2.2strcpy? It’s just that there is an extra n in the middle of strncpy. The difference between this function and strcpy is that there is an extra n at the end. The usage of parameters size_t num, is not much different from strcpy above, except that the programmer can adjust the number of operating characters. The code is as follows:

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	char* pf = strncpy(arr1, arr2, 3);
	printf("%s" , pf);
	return 0;
}


! 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, append 0 to the end of the target until num.

2.6 strncat

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

 ~Appends the first num characters of source to destination, plus a terminating null-character.
~If the length of the C string in source is less than num, only the content up to the terminating
null-character is copied.

Appends the first num characters of the source to the destination, plus a terminating null character. If the length of the C string in the source is less than num, only the contents before the terminating null character are copied.

 It is not much different from the above2.3strcat, it just has one more parametersize_t num, The code is as follows:

int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	char* pf = strncat(arr1, arr2, 2);
	printf("%s" , pf);
	return 0;
}

2.7 strncmp

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

followed by2.4 strcmpIt’s similar, right? Directly upload the code:

int main()
{
	char arr1[1000] = { "abcdefg" };
	char arr2[] = { "cccc" };
	int ret = strncmp(arr1, arr2, 2);
	printf("%d" , ret);
	return 0;
}

2.8 strstr

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

Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of
str1.

Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

 This function is to find a string in a string. Find the position where str2 first appears in str1, and then return a pointer to that position. If not, return NULL. Look at the code:

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

 

2.9 strtok 

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

This function is used to cut strings 

! The sep parameter is a string, which defines the set of characters used as separators. The first parameter specifies a string, which contains 0 or more by one or more of the sep string. Tags separated by delimiters
.
!  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 manipulated string, so the strings split using the strtok function are generally the contents of temporary copies
and can Modified.)
! The first parameter of the strtok function is not NULL, the function will find the first mark in str, and the strtok function will save its position in the string
.
! The first parameter of the strtok function is NULL, and the function will search for the next mark
starting from the saved position in the same string.
! If there are no more tokens in the string, a NULL pointer is returned

Look at the code:

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

 

#include <stdio.h>
int main()
{
    char *p = "[email protected]";
    const char* sep = ".@";
    char arr[30];
    char *str = NULL;
    strcpy(arr, p);//将数据拷贝一份,处理arr数组的内容
    for(str=strtok(arr, sep); str != NULL; str=strtok(NULL, sep))
    {
        printf("%s\n", str);
    }
}

 

2.10 strerror 

 char * strerror ( int errnum );

Returns the error code and corresponding error information.
 This function will translate the error code into an error message.

code show as below:

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

 When using library functions in C language, if an error occurs, the error code will be placed in the errno variable. errno is a global variable and can be used directly.

perror directly prints the error information corresponding to the error code. The printing rules are: print the custom information first: xxx

For example: perror("Print error message"). perror is equivalent to printf + strerror

2.11 memcpy

void * memcpy ( void * destination, const void * source, size_t num );
 ! The function memcpy copies num bytes of data starting from the source location to the destination memory location.
 ! This function will not stop when encountering '\0'.
 ! If there is any overlap between source and destination, the results of copying are undefined.

code show as below:

/* 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.12 memmove

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

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

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

2.13 memcmp

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

! Compare num bytes starting from the ptr1 and ptr2 pointers
! 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;
}

The simulation implementation of the library function will be released in the next blog, thank you for reading.​ 

Guess you like

Origin blog.csdn.net/A1546553960/article/details/133957630