C language - character functions and string functions

This article introduces the use and precautions of library functions dealing with characters and strings The processing ...
1.strcpy
2.strcat
3.strcmp
1.strncpy
2.strncat
3. strncmp
1.strstr
2.strtok
strerror
1. Character classification function:
2. Character conversion:
1.memcpy
2.memmove
3.memset
4.memcmp

This article introduces the use and precautions of library functions dealing with characters and strings
The processing of characters and strings in C language is very frequent, but C language itself has no string type. Strings are usually placed in constant strings or character arrays.
String constants apply to string functions that do not modify them

1, Find string length strlen


Points to note:
1. The string has' \ 0 'as the end flag. strlen function returns the number of characters 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)
Look at the following code:

#include <stdio.h> int main() { if (strlen("abc")-strlen("abcdef")) { printf("1"); } else { printf("2"); } return 0; }

The print result is: 1
Because the returned results of two strlen in if are of size_t type, the subtraction is also unsigned
4. Simulation implementation of strlen function:

#include<stdio.h> int my_strlen(const char*str) //const modifies a read-only variable to prevent the variable from being changed { int count = 0; while (*str++)//When * str =' str = '\ 0'' jumps out of the loop, note that * str + + operator + + takes precedence over * operator { count++; } return count; } int main() { char*p = "abcd\0e";//Encountered '\ 0' stop count printf("%d",my_strlen(p)); return 0; }
2, String function with unlimited length

1.strcpy

String copy

The source string must end with '\ 0'. The '\ 0' in the source string will be copied to the destination space.
The destination space must be large enough to hold the source string. The destination space must be variable.
Simulation Implementation:
There are three ways:
Mode 1:

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

Mode 2:

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

Mode 3:

//Pointer - pointer mode int my_strlen(char *s) { char *p = s; while(*p != '\0' ) p++; return p-s; }

2.strcat

String concatenation
The source string must end with '\ 0'.
The target space must be large enough to accommodate the contents of the source string.
The target space must be modifiable.
Simulation Implementation:

//strcat returns the address of the starting space char* my_strcat(char* dest, const char* src) { assert(dest && src); char* ret = dest; //End of destination string found \ 0 while (*dest) { dest++; } //Append source string until \ 0 while (*dest++ = *src++) { ; } return 0; }

3.strcmp

Is the content of the comparison string, not the length
Standard provisions:
If the first string is greater than the second string, a number greater than 0 is returned
If the first string is equal to the second string, 0 is returned
If the first string is less than the second string, a number less than 0 is returned
Simulation Implementation:

int my_strlen(const char* s1, const char* s2) { assert(s1 && s2); while (*s1 == *s2) { if (*s1 == *s2) return 0; s1++; s2++; } return *s1 - *s2; }
3, Introduction to string functions with limited length

1.strncpy

1. Copy num characters from the source string to the target 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. Simulation Implementation:

//1. Parameter sequence //2. Function of function, stop condition //3.assert //4.const modifier pointer //5. Function return value //6. The title comes from the final part of the book "high quality C/C + + Programming" char *my_strcpy(char *dest, const char*src) { char *ret = dest; assert(dest != NULL); assert(src != NULL); while((*dest++ = *src++)) { ; } return ret; }

2.strncat

Simulation Implementation:

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

3. strncmp

The comparison shows that another character is different, or a string ends, or num characters are all compared.

Simulation Implementation:

int my_strcmp (const char * src, const char * dst) { int ret = 0 ; assert(src != NULL); assert(dest != NULL); while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst) ++src, ++dst; if ( ret < 0 ) ret = -1 ; else if ( ret > 0 ) ret = 1 ; return( ret ); }

4, String lookup

1.strstr

Find substrings in a string
Simulation Implementation:

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); }

2.strtok

1. The SEP parameter is a string that defines the set of characters used as separators
2. The first parameter specifies a string that contains 0 or more tags separated by one or more separators in the sep string.
3. 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 of the content and can be modified.)
4. The first parameter of strtok function is not NULL. The function will find the first tag in str, and strtok function will save its position in the string.
5. The first parameter of strtok function is NULL. The function will start at the saved position in the same string to find the next tag.
6. If there are no more tags in the string, a NULL pointer is returned.

#include <stdio.h> int main() { char *p = "[email protected]"; const char* sep = ".@"; char arr[30]; char *str = NULL; strcpy(arr, p);//Copy the data and process the contents of the arr array for(str=strtok(arr, sep); str != NULL; str=strtok(NULL, sep)) { printf("%s\n", str); } }
5, Error message report

strerror


Returns the error information corresponding to the error code

/* strerror example : error list */ #include <stdio.h> #include <string.h> #Include < errno. H > / / header files that must be included 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; } Edit & Run
6, Character operation

1. Character classification function:

Function returns true if its arguments meet the following conditions
iscntrl any control character
isspace blank characters: space ',' page feed '\ f', line feed '\ n', carriage return '\ r', tab '\ t' or vertical tab '\ v'
isdigit decimal digits 0 ~ 9
isxdigit hexadecimal digit, including all decimal digits, lowercase AF and uppercase AF
islower small letter a~z
isupper capital letters A~Z
isalpha letter AZ or AZ
isalnum letter or number, az,AZ,0~9
ispunct punctuation mark, any graphic character not belonging to numbers or letters (printable)
isgraph any graphic character
Isprintany printable character, including graphic characters and white space characters

2. 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; }
7, Memory operation function

1.memcpy

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

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); }

2.memmove

void * memmove ( void * dst, const void * src, size_t count) { void * ret = dst; if (dst <= src || (char *)dst >= ((char *)src + count)) { /* * Non-Overlapping Buffers * copy from lower addresses to higher addresses */ while (count--) { *(char *)dst = *(char *)src; dst = (char *)dst + 1; src = (char *)src + 1; } } else { /* * Overlapping Buffers * copy from higher addresses to lower addresses */ dst = (char *)dst + count - 1; src = (char *)src + count - 1; while (count--) { *(char *)dst = *(char *)src; dst = (char *)dst - 1; src = (char *)src - 1; } } return(ret); }

3.memset

4.memcmp

Compare num bytes starting from ptr1 and ptr2 pointers

15 October 2021, 19:10 | Views: 8484

Add new comment

For adding a comment, please log in
or create account

0 comments