strcmp in C – How to Compare Strings in C (2024)

Strings are used to store text or characters. In C programming string is a sequence of characters ending with a null character \0. This null character indicates the termination of the string. Strings are a type of one-dimensional character array or a collection of character values. The basic syntax to declare a string is defined as

char string_name[size];

Here string_name is the name of the string variable and size defines the length of the string.

Example: char name[10] = “BEAUTIFUL”;

Or

char name[ ] = “BEAUTIFUL”;

In this example, a string is declared with the identifier “name”. The string is initialized to “BEAUTIFUL”. The compiler will automatically put a null character after the last character of the string. If the size is not mentioned then the compiler will calculate the size by itself. By adding one more value to the number of characters length of the string can be calculated.

Example: C program to represent string initialization.

#include <stdio.h>Void main(){char name[5] = “GOOD”;printf( “%s \n”, name);return 0;}

Output:

After execution, the output will beGOOD

String comparison in Cis used to check the plagiarism of documents, compare the passwords while signing in, etc. In the next section, a full description is given related toString Comparison in C,string comparison in c without using strcmp,string comparison in Cwithout using library function, examples of string comparison, etc.

What is String Comparison in C?

To detect if two strings are identical or not string comparison is used. This is executed by utilizing some built-in function or by comparing every character of both strings.

To compare the strings in the C programming language 4 basic methods are used.

  • String comparison by using strcmp() String Library function.

  • String comparison without using strcmp() function .

  • String comparison by using pointers.

  • String comparison by using recursion.

Methods of string comparison in C

There are various methods of string comparison in C as mentioned below:

  • String comparison by using strcmp() String Library function

The string.h header file consists of some predefined string library functions. The string library functions are used for operations on strings. strcmp() is a predefined library function that is used to compare two strings. Two strings are given to the strcmp() function as input arguments. The function then compares both strings lexicographically. It returns an integer value of zero, a positive value, and a negative value as a result. The syntax used to define strcmp() function is presented as

int strcmp (const char* stng1, const char* stng2);

Here two inputs string1 and string2 are passed as strings. The int signifies that the output of strcmp function is an integer value. The result after the comparison of both strings depends on 3 different cases which are listed below.

1. The return value is 0 when both strings are identical.

2. Returns a positive value if a character's ASCII value in the first string is bigger than a character's ASCII value in the second string.

3. Return a negative value if the ASCII value of a character in the first string is smaller than the ASCII value of a character in the second string.

Example:

#include <stdio.h>#include <string.h>int main(){char stng1[20];char stng2[20];int var;printf(“Enter first string:”);scanf(“%s”, stng1);Printf(“Enter second string:”);scanf(“%s”, stng2);var = strcmp(stng1, stng2);if(var ==0)printf (“strings are equal”);elseprintf (“strings are not equal”);return 0;}

Output:

Enter first string: morningEnter second string: nightstrings are not equal

Algorithm:

1. Two character arrays stng1 and stng2 are declared.

2. printf and scanf functions are used to take input from the user.

3. strcmp() function is used to compare the above two strings stng1 and stng2.

4. After execution if the function returns 0 then both strings are equal else strings are not equal.

Keynotes:

1. Here stdio.h means single input single output. This is a built-in header file in the C programming language. It contains information related to input and output functions.

2. Printf is an output function that indicates “print formatted”.

3. Scanf is an input function that is used to read input from the user.

4. Int main() function is used as the starting point of program execution. It directs the calls to other functions in the program and thus controls program execution.

  • String comparison without using strcmp() function

String comparison without using strcmp() function is possible. String comparison can be done by using a loop. In this process, two strings are compared by traversing each index using a loop and equating every character one after another.

Example:

#include <stdio.h>int StringComparison(char[], char[]);int main(){char stng1[20];char stng2[20];int var;printf(“Enter first string:”);scanf(“%s”, stng1);Printf(“Enter second string:”);scanf(“%s”, stng2);var = StringComparison (stng1, stng2);if(var ==0)printf (“strings are equal”);elseprintf (“strings are not equal”);return 0;}int StringComparison(char a[], char b[]){int flag=0,i=0;while (a[i]!=’\0’ &&b[i]!=’\0’){If(a[i]!= b[i]){flag = 1;break;}i ;}if (a[i]!=’\0’ ||b[i]!=’\0’)return1;if(flag==0)return 0elsereturn1;}

Output:

Enter first string: goodEnter second string: excellentstrings are not equal

Algorithm:

1. Two character arrays stng1 and stng2 are declared.

2. A function named StringComparison() is built. 2 strings are given as arguments to the function.

3. Then a while loop is formed to compare the characters one by one. The strings are identical if the function returns 0 otherwise the strings are not identical.

  • String comparison by using pointers

Example:

#include <stdio.h>int StringComparison(char *, char *);int main(){char stng1[20];char stng2[20];int var;printf(“Enter first string:”);scanf(“%s”, stng1);Printf(“Enter second string:”);scanf(“%s”, stng2);var = StringComparison (stng1, stng2);if(var ==0)printf (“strings are equal”);elseprintf (“strings are not equal”);return 0;}int StringComparison(char *a, char *b){int flag = 0;while (*a != ‘\0’ && *b != ‘\0’){if (*a != *b){flag = 1;}a ;b ;}if(*a != ‘\0’ || *b != ‘\0’)return 1;if (flag ==0)return 0;elsereturn 1;}

Output:

Enter first string: constructEnter second string: developstrings are not equal

Algorithm:

1. Two character arrays stng1 and stng2 are declared.

2. A function named StringComparison() is built. 2 strings are given as arguments to the function.

3. The address of ” stng1” is stored in ‘a’ pointer and the address of “stng2” is stored in ‘b’ pointer.

4. Inside the function a while loop is formed which runs until the pointer a or b does not reach a null character.

  • String comparison by using recursion

The recursion function is also used to compare two strings. Here lengths of both strings. Then a function is built which keeps calling itself until it meets the desired criteria.

Example:

#include<stdio.h>#include<string.h>Int StringComparison(char stng1[ ], char stng2[ ]){static int i = 0;int x = strlen(stng1);int y = strlen(stng2);static int c = 0;if (x != y){return 0;}else if (i < x){if (stng1[i] == stng2[i])c ;i ;StringComparison(stng1, stng2);}if (c ==i){return 1;}return 0;}int main(){char stng1[20], stng2[20], c;printf(“Enter first string”);fgets(stng1, 20, stdin);printf(“Enter second string”);fgets(stng2, 20, stdin);c = StringComparison(stng1, stng2);if (c){printf(“Strings are equal”);else{printf(“strings are not equal”);}return 0;}}}

Output:

Enter first string constructEnter second string constructStrings are equal

Algorithm:

1. Two character arrays stng1 and stng2 are declared.

2. A function named StringComparison() is built. The length of both strings is computed using stlen() function. If lengths are equal StringComparison() function will return 0.

3. If the lengths are equal then the characters are compared. The first character of stng1 i.e. stng1[i] is compared with the first character of stng2 i.e. stng2[i]. If both characters are the same the value of the count is increased by 1.

4. The function will keep calling itself until it meets the required criteria i.e. i < x is false.

5. If c = i it signifies the strings are equal and the StringComparison() function will return 0.

6. If the strings are not equal the StringComparison() function will return 1.

Conclusion

A brief idea about the string function is given in the beginning. Then various methods are discussed to compare two strings. The significance of strcmp() function is explained. A comparison of two strings without using a library function is represented. Also Comparison of two strings using pointers and recursion are depicted.

FAQs

1. What are strings?

Strings are used to store text or characters. In C programming string is a sequence of characters ending with a null character \0. Strings are a type of one-dimensional character array or a collection of character values.

2. What is the significance of a null character?

This null character indicates the termination of the string.

3. What is the syntax to define a string?

The basic syntax to declare a string is defined as

4. What is the char string_name[size];?

Here string_name is the name of the string variable and size defines the length of the string

5. What is string comparison in C?

To detect if two strings are identical or not string comparison is used. This is executed by utilizing some built-in function or by comparing every character of both strings.

6. What is strcmp()?

Strcmp() is a predefined library function that is used to compare two strings.

7. What is the syntax to define strcmp()?

The syntax used to define strcmp() function is presented as

int strcmp (const char* stng1, const char* stng2);

Here two inputs string1 and string2 are passed as strings. The int signifies that the output of strcmp function is an integer value.

8. What is stdio.h?

Here stdio.h means single input single output. This is a built-in header file in the C programming language. It contains the information related to input and output functions.

9. What is string.h?

The string.h header file consists of some predefined string library functions. The string library functions are used for operations on strings.

10. What is int main ()?

Int main() function is used as the starting point of program execution. It directs the calls to other functions in the program and thus controls program execution

11. What is printf?

Printf is an output function which indicates “print formatted”.

12. What is scanf?

Scanf is an input function which is used to read input from the user.

strcmp in C – How to Compare Strings in C (2024)

FAQs

Strcmp in C – How to Compare Strings in C? ›

We take the user input as strings. We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

How to compare two strings using strcmp in C? ›

We take the user input as strings. We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

How to compare to strings in C? ›

The strcmp() function, is used to compare the strings (str1,str2). The strings str1 and str2 will be compared using this function. If the function returns a value 0, it signifies that the strings are equal otherwise, strings are not equal.

How to compare a string to multiple strings in C? ›

You need to use strcmp to compare in C. "==" will point to the memory addres in case of arrays and strings in C..instead you can use strcmp function. To compare two strings, we can use the strcmp() or strncmp() functions.

Can you compare two strings using the == operator in C? ›

The answer to your question is no, we cannot compare two strings using == in C because a string in C language is an array of characters and the name of the string (name of the variable which is pointing the string's character array) is itself a pointer to character (char) which points the very first element(character) ...

Can you use == to compare two strings? ›

== is an operator that returns true if the contents being compared refer to the same memory or false if they don't. If two strings compared with == refer to the same string memory, the return value is true; if not, it is false. The return value of == above is false, as "MYTEXT" and "YOURTEXT" refer to different memory.

How to check if a string contains another string in C? ›

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.

How to compare two strings in C without case sensitive? ›

strcmpi() — Compare Strings Without Case Sensitivity

h> int strcmpi(const char *string1, const char *string2); Note: The strcmpi function is available for C++ programs. It is available for C only when the program defines the __cplusplus__strings__ macro.

What is the best way to compare two strings? ›

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

How do you compare two strings the same? ›

You can compare two strings for equality with the == and === operators. These operators differ in how they deal with non-string operands. The == operator casts non-string operands to strings, so it reports that 3 and "3" are equal. The === operator does not cast, and returns false if the types of the arguments differ.

How do you compare two strings for similarity? ›

Longest common substring/subsequence similarity

The similarity score can be computed by dividing the length of the longest common substring by the length of the longest string.

What is the operator to compare two strings? ›

You use the relational (comparison) operators =, <>, ><, <, <=, =<, >, >=, and => to ascertain the relative positions of two strings in ASCII sort order. The result of comparing two strings in this way is a value of True, False, or NULL (if one of the operands is NULL).

How to concatenate two strings in C without using strcat? ›

Concatenating Two Strings in C

Iterate the first string and find the end where a null-terminator is encountered. Now, copy the second string to the first string starting from the found position. Finally, add a null terminator at the end of the concatenated string.

How to concatenate two strings? ›

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time. The C# examples in this article run in the Try.NET inline code runner and playground.

What is the strcmp function used to compare two strings? ›

C strcmp() function works by comparing the two strings lexicographically. It means that it compares the ASCII value of each character till the non-matching value is found or the NULL character is found.

What is strcmpi() in C? ›

Description. strcmpi compares string1 and string2 without sensitivity to case. All alphabetic characters in the two arguments string1 and string2 are converted to lowercase before the comparison.

What does strcmp () function return if the two strings are identical? ›

The return value from strcmp is 0 if the two strings are equal, less than 0 if str1 compares less than str2 , and greater than 0 if str1 compares greater than str2 .

Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6417

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.