How to compare two strings in the C programming language

Table of contents:

How to compare two strings in the C programming language
How to compare two strings in the C programming language
Anonim

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. You need a special function to compare strings - don't use! = Or ==.

Steps

Compare Two Strings in C Programming Step 1
Compare Two Strings in C Programming Step 1

Step 1. The C programming language includes two functions with which you can compare string lengths

Both of these functions are included in the library.

  • strcmp () - This function compares two strings and returns the difference in number of characters.
  • strncmp () - This function is similar to strcmp () except that the first n characters are compared. It is considered more secure because it avoids overflow failures.
Compare Two Strings in C Programming Step 2
Compare Two Strings in C Programming Step 2

Step 2. Start the program with the required libraries

You will need libraries and, as well as any other libraries required for your particular program.

#include #include

Compare Two Strings in C Programming Step 3
Compare Two Strings in C Programming Step 3

Step 3. Enter the int function

It returns an integer as a result of comparing the length of two strings.

#include #include int main () {}

Compare Two Strings in C Programming Step 4
Compare Two Strings in C Programming Step 4

Step 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 #include int main () {char * str1 = "apple"; char * str2 = "orange"; int ret; }

Compare Two Strings in C Programming Step 5
Compare Two Strings in C Programming Step 5

Step 5. Enter the comparison function

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

#include #include int main () {char * str1 = "apple"; char * str2 = "orange"; int ret; ret = strncmp (str1, str2, 8); / * Compares two strings that are no more than 8 characters long * /}

Compare Two Strings in C Programming Step 6
Compare Two Strings in C Programming Step 6

Step 6. Enter the conditional If

… Else. It is needed to show which line is longer. The strncmp () function will return 0 if the string lengths are the same, a positive number if str1 is longer, and a negative number if str2 is longer.

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

Popular by topic