How to Compare Two Strings in C Programming Language: 10 Steps (with Pictures)

Table of contents:

How to Compare Two Strings in C Programming Language: 10 Steps (with Pictures)
How to Compare Two Strings in C Programming Language: 10 Steps (with Pictures)
Anonim

Comparing the length of strings is a commonly used function in the C programming language because it allows you to determine which string contains more characters. This is particularly useful for sorting data. Comparing strings requires a special function; so don't use: != or ==.

Steps

Compare Two Strings in C Programming Step 1

Step 1. There are two functions that allow you to compare strings in C

Both are included in the code library.

  • strcmp() – This function compares two strings and returns the difference in the number of characters.
  • strncmp() – This also applies to strcmp(), except it compares the first n characters. It is considered more secure as it helps prevent crashes due to overflow.
Compare Two Strings in C Programming Step 2

Step 2. Launch the program with the necessary libraries

You will need both the libraries and, along with other libraries that you may need for your program.

#include #include

Compare Two Strings in C Programming Step 3

Step 3. Launch a

int function.

This is the easiest way to learn this function because it returns an integer comparing the length of the two strings.

#include #include int main() { }

Compare Two Strings in C Programming Step 4

Step 4. Decide which two strings you want to compare

In this example we are comparing two given char strings. You also need to determine 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

Step 5. Add the compare function

Now that you have defined two strings, you can add the compare function. We're going to use strncmp() so we need to make sure the number of characters to measure is set within the function.

#include #include int main() { char *str1 = "apple"; char *str2 = "orange"; int ret; ret = strncmp(str1, str2, 11); /*Compare the two strings up to 11 characters in length */ }

Compare Two Strings in C Programming Step 6

Step 6. Use

If…Else to perform the comparison.

Now that we've created the function, use If…Else to determine which string is longer. strncmp() returns 0 if the strings are the same length, 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, 11); if(ret > 0) { printf("str1 is longer"); } else if(ret < 0) { printf("str2 is longer"); } else { printf("The two strings are equal "); } return(0); }

Popular by topic