How to compare two strings in the C programming language

Author: William Ramirez
Date Of Creation: 18 September 2021
Update Date: 1 July 2024
Anonim
C_68 C program to Compare two Strings | with strcmp() and without strcmp() function
Video: C_68 C program to Compare two Strings | with strcmp() and without strcmp() function

Content

It is quite common in C code to compare string lengths to find out which string contains more characters. This is useful for sorting data. A special function is needed to compare strings - don't use != or ==.

Steps

  1. 1 The C programming language includes two functions that you can use to compare string lengths. Both of these functions are included in the library string.h>.
    • strcmp () - this function compares two strings and returns the difference in the number of characters.
    • strncmp () - this function is the same as strcmp () except that the first n characters. It is considered more secure because it avoids overflow failures.
  2. 2 Start the program with the required libraries. You will need libraries stdio.h> and string.h>as well as any other libraries required for your specific program.

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

  3. 3 Enter function int. It returns an integer as a result of comparing the length of two strings.

    #include stdio.h> #include string.h> int main () {}

  4. 4 Identify the two strings you want to compare. In our example, let's compare two strings of type char... Also define the return value as an integer.

    #include stdio.h> #include string.h> int main () {char * str1 = "apple"; char * str2 = "orange"; int ret; }

  5. 5 Enter a comparison function. In our example, we will use the function strncmp ()... In it you need to set the number of measured characters.

    #include stdio.h> #include string.h> int main () {char * str1 = "apple"; char * str2 = "orange"; int ret; ret = strncmp (str1, str2, 8); / * Compares two strings up to 8 characters long * /}

  6. 6 Enter a conditional statement If... Else. It is needed to show which line is longer. Function strncmp () will return the number 0if the lengths of the strings are the same, a positive number if str1 is longer, and a negative number if str2 is longer.

    #include stdio.h> #include string.h> int main () {char * str1 = "apple"; char * str2 = "orange"; int ret; ret = strncmp (str1, str2, 8); if (ret> 0) {printf ("str1 is longer"); } else if (ret 0) {printf ("str2 is longer"); } else {printf ("Line lengths are equal"); } return (0); }

Warnings

  • Remember that if the lengths of the strings are equal, the value 0 will be returned. This can be confusing because 0 is also FALSE.