Talk about the use and attention of common string functions in C language (strlen,strcpy,strcmp,strcat)

Posted by greenie__ on Tue, 21 Sep 2021 06:20:18 +0200


String functions in c language are difficult to maintain and use. It is often necessary to consider whether they cross the boundary and the position of 0. Sometimes, when some compilers use string functions in c language, the compiler will warn you ⚠ Prompt that the function is unsafe;

Even many object-oriented languages, such as Java and C + +, have their own string classes to maintain all aspects of strings;

In contrast, it seems that the string function of C language is really vulnerable. Ha ha, it can be understood, but it is still necessary to learn. Let me understand what the string function of C language is.

How does C language represent strings

First, we should clarify two concepts, character and string:
A string is a string composed of a bunch of characters and ending with \ 0;
A character is simply a single character.

Because C language has only character type char, but no string type;
Therefore, there are different ways to save strings in C language:
const char* str = “abcdef”; // Save the first address of the string "ABCDEF" using const char * pointer type to represent the string
char str[ ] = “abcdef”; // Use char [] character array to save the string "ABCDEF";

General classification of common string functions

  • Find string length


  • String function with unlimited length
    Unlimited length means that you can directly copy, append, or compare with the destination string according to the source string you give me;


  • Introduction to string functions with limited length
  • The length hand limited string function is that the source string specifies the length to the destination string according to the wishes of the caller for copying, appending and comparing operations.


  • String lookup


  • Error message report


Recommend a website for C/C + + library functions. You can find any functions that can't be found here:

Find the length of the string -- the use and attention of strlen

Let's see how the prototype of the library function defines it

The above figure also has some English, which is probably to explain what to pay attention to and how to use this function.
Let's look at the function prototype

size_t strlen(const char* str);
Parameter interpretation:
size_t yes strlen The return type of a function is essentially unsigned int Type, i.e. unsigned type;
From the designer's point of view, he clearly knows that the length of the string function cannot be negative, so the design is size_t It's also reasonable.

const char* str Add here const From the perspective of function design, people don't want the string passed in to be modified,
Why don't designers want this string to be modified? Because the designer knows that there is no need to change the size of the string to find the length of the string,
So add const,Ensure that the string passed in by the string is inadvertently modified when designing this function.

Do some examples to show how to use the strlen function

//First, we want to use this function when we need the length of the string
 The first way:
const char* str = "abc";

//Accept size with int_ T is no problem. It's just type conversion.
//Also, we should understand that strlen is to find the length of the string. Although the string "abc" hides a \ 0, its size is 4 and its length is 3
//The string length does not include \ 0, which is a flag to indicate the end of the string; However, the existence of \ 0 should be considered when calculating the size
int len = strlen(str);//The answer is 3
The second way:
//It is also possible to pass a string constant directly to the strlen function, that is, it does not have to pass a variable
int len2 = strlen("abc"); //Answer 3
//Why can it be passed like this? The function parameter type of strlen is const char *, and the string constant is also const char *
The third way:
//It is also possible to use the form of an array
char [] str3 = "abc";
int len3 = strlen(str3); //Answer 3

Notes: Notes on the use of strlen

First: when strlen calculates the string length, it calculates the length of the character combination parameter string before \ 0, excluding \ 0, which is a flag representing the end of the string.

int len = str("abc\0def");The answer is 3,Not 7, not 8, not 9

Second: the return type of the string is size_t, when using string subtraction, the result is negative, but due to size_t is an unsigned type, and you end up with a positive number.

if(strlen(abc) - strlen(defg) < 0){
	return 1;
	return 0;
The above result returns 0,Don't think 3 -4 = -1 ; -1<0 If it is established, return to 1,
because strlen The return type of is size_t,therefore-1 It will eventually be transposed into an unsigned number, which is a very large positive number.

String copy function -- use and attention of strcpy

String copy function. Similarly, look at the library function and its prototype

The function copies the source string source to the destination string destination, including \ 0 of the source string source, and returns the first address of the copied string.

char* strcpy(char* destination,const char* source)
Parameter interpretation:
char* Use to accept the copied string
destination and source Is to string source copy to destination String go

In fact, there is an implied meaning here. Destination no matter what the string in you is, when I copy the string source, the strcpy function returns the source string, and the string space implied destination should be large enough, at least as large as source.

strcpy usage example:

#Include < string. H > / / all strings in C language should contain the header file
int main()
	 char str1[] = "xxxxxxxxxx";
	 char str2[] = "hello";
	 strpty(str1,str2); //Copy string str1 to str2	
	 return 0;

Let's debug:
Before commissioning:

After debugging, that is, the changes after the strcpy function is executed

Obviously, the copy was successful.

Precautions for using strcpy function:

First, the destination string of the copied string must be passed as an array, and the parameter cannot be passed as a string pointer const char *;

const char* str1 = "xxxxxxxxxx";
const char* str2 = "hello";

//An error will be reported because str1 is const char * type and cannot be modified. When you copy str2 and try to modify the contents of str1, an error will be reported

Screenshot of error report:

Note 2: the destination string is at least larger than the space of the source string.

	char str1[] = "xxxx"; //Space size 5
	char str2[] = "helloworld";//Space size 11

	//str2 can copy str1; However, the space size of str2 is larger than str1, indicating that \ 0 of str2 has not been copied;
	//This will result in failure to access \ 0 when using str1, resulting in an error

Something went wrong!

Note 3: the source string must end with \ 0.

	char sr1[] = "abcdefg";
	char str2[] = {'a','b','c'};//There is no end to \ 0 in this way

Screenshot of error reporting:

String comparison function -- use and attention of strcmp

The function of strcmp: compare the string str1 and the string str2. If the two strings are equal, it returns 0, str1 > str2 returns a number greater than 0, and str1 < str2 returns a number less than 0; The string compares not the length of the string, but the ASCII value of the corresponding characters of the two strings.

strcmp use case:

char str1[] = "abcdef";
char str2[] = "abcg";

strcmp(str1,str2);//str1 is less than str2, so a number less than zero is returned

Note: when comparing two strings, use the strcmp function instead of subtracting strings. This is experience.

String append function -- use and attention of strcat

strcat function function: append a source string source to the destination string destination; The append process is to find the \ 0 of the destination, then overwrite the \ 0 of the destination with the first character of the source, and then append other characters to the destination successively until the append to the \ 0 of the source stops. The function returns the appended string address destination.

Use cases of strcat:

char str1[20] = "abcdef";
char str2[] = "ghij";

char* str3 = strcat(str1,str2);//Append str1 to the string str2;
								//str3 = "abcdefghij";

Precautions for using functions:

First, the destination string destination must have enough space to accommodate the appended string;

Error case:
char str1[] = "abcdef";
char str2[] = "ghij";

char* str3 = strcat(str1,str2); //Error: the space size of str1 is only 7. Adding str2 must have failed in the past

There must be an error in this append method, because str1 has no end of \ 0, and an error will occur when accessing str1, which is out of bounds

Note 2: the target space must be modifiable. The string of const char * pointer type cannot be used to pass parameters to the first parameter of strcat

Finding substrings of strings -- the use and attention of STR

strstr function function: find out whether str1 contains continuous substring str2. If found, return the first address of str2 in str1. If not, return NULL.

Use case:

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

int main ()
  char str[] ="This is a simple string";
  char * pch= strstr (str,"simple");;
  if (pch != NULL)
  return 0;

Note: the search is for continuous substrings, not pieced together.

Topics: C