×

What is String Comparison in C

String comparison is the process of comparing two strings (sequences of characters) to determine if they are equal, or if one is greater or less than the other. The comparison is typically based on the Unicode values of the characters in the strings, so that a string that comes first in a dictionary or alphabetical ordering is considered "less" than one that comes later. The result of a string comparison is usually represented as either equal (0), less than (-1), or greater than (1). This can be useful in various programming applications, such as sorting and searching, or for checking user input to see if it matches a predefined string.

There are several methods for comparing strings in different programming languages:

  • Built-in functions: Many programming languages have built-in functions for string comparison, such as strcmp() in C, strcoll() in C++, or strcmp() in Python.
  • Operators: Some programming languages have operators for string comparison, such as the equality (==) and inequality (!=) operators in many languages.
  • Custom functions: You can write your own custom functions to compare strings by iterating over the characters in the strings and checking their values.
  • Regular expressions: Regular expressions can be used to compare strings in a more sophisticated way, matching patterns in the strings rather than simple character-by-character comparisons.
  • Library functions: Some programming languages have libraries that provide additional functions for string comparison, such as the StringUtils class in Java or the stringr package in R.

String Comparison in C

In the C programming language, string comparison is the process of comparing two strings (i.e. arrays of characters) to determine if they are equal or not. The standard function for string comparison in C is strcmp(). The function takes two string parameters as input and returns 0 if both strings are equal, a negative value if the first string is lexicographically less than the second, and a positive value if the first string is lexicographically greater than the second.


In C language, there are several methods for string comparison, including:

1. strcmp(): This is the standard library function for string comparison in C. It takes two strings as arguments and compares them character-by-character until it finds a difference or reaches to the end of one of the strings. If both strings are equal, it returns 0. If the first string is lexicographically less than the second, it returns a negative value. If the first string is lexicographically greater than the second, it returns a positive value.

Example:

#include <string.h>
#include <stdio.h>
int main()
{
char str1[10] = "Hello";
char str2[10] = "World";
int result = strcmp(str1, str2);
if (result == 0)
printf("Strings are equal.\n");
else if (result < 0)
printf("str1 is lexicographically lesser than str2.\n");
else
printf("str1 is lexicographically greater than str2.\n");
return 0;
}

Output:

str1 is lexicographically lesser than str2.

2. Custom String Comparison: You can write your own custom function to compare strings by iterating over the characters in the strings and checking their values.

Example:

#include <stdio.h>
int compare_strings(const char *str1, const char *str2)
{
while (*str1 != '\0' && *str2 != '\0')
    {
if (*str1 < *str2)
return -1;
else if (*str1 > *str2)
return 1;
str1++;
str2++;
    }
if (*str1 == '\0' && *str2 == '\0')
return 0;
else if (*str1 == '\0')
return -1;
else
return 1;
}
int main()
{
char str1[10] = "Hello";
char str2[10] = "World";
int result = compare_strings(str1, str2);
if (result == 0)
printf("Strings are equal.\n");
else if (result < 0)
printf("str1 is lexicographically lesser than str2.\n");
else
printf("str1 is lexicographically greater than str2.\n");
return 0;
}

Output:

str1 is lexicographically lesser than str2.

3. strncmp(): This function is similar to strcmp(), but only compares the first n characters of the strings. This can be useful if you only want to compare a certain prefix of the strings, or if you want to avoid buffer overflow issues.

Example:

#include <string.h>
#include <stdio.h>
int main()
{
char str1[10] = "Hello";
char str2[10] = "World";
int result = strncmp(str1, str2, 4);
if (result == 0)
printf("First 4 characters are equal.\n");
else if (result < 0)
printf("str1 is lexicographically lesser than str2.\n");
else	
printf("str1 is lexicographically greater than str2.\n");
}

Output:

str1 is lexicographically lesser than str2.

4. Using Recursion in C: In C language, string comparison can also be performed using recursion. This involves dividing the problem of comparing two strings into smaller subproblems, by comparing the first characters of each string, and then recursively calling the function on the remaining characters in each string.

Example:

#include <stdio.h>
int compare_strings(const char *str1, const char *str2)
{
if (*str1 == '\0' && *str2 == '\0')
return 0;
else if (*str1 == '\0')
return -1;
else if (*str2 == '\0')
return 1;
if (*str1 < *str2)
return -1;
else if (*str1 > *str2)
return 1;
else
return compare_strings(str1 + 1, str2 + 1);
}
int main()
{
char str1[10] = "Hello";
char str2[10] = "World";
int result = compare_strings(str1, str2);
if (result == 0)
printf("Strings are equal.\n");
else if (result < 0)
printf("str1 is lexicographically lesser than str2.\n");
else
printf("str1 is lexicographically greater than str2.\n");
return 0;
}

Output:

str1 is lexicographically lesser than str2.

Related Topics

Fibonacci series program in C using Recursion

In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language. What does the term "Fibonacci Series" mean? The following number in a Fibonacci number series is...

2 minutes read.

Explain the two-way selection in C

In C programming, a two-way selection statement is used to choose between two different options based on a Boolean expression. The two-way selection statement in C is the if statement. The...

6 minutes read.

Example of Iteration in C

The iterations in the C language are the statements which are executed number of times until a certain condition is reached. These iterations are regarded as “Loops” in C language....

3 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

Associativity of Operators in C

What is an Associativity operator? Two operators with equal priority are connected by employing their association when they are present in an expression. There are two different types of associativity: left to rightright...

4 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

Inline Function in C

Inline Function in C A normal function will become an inline function when the function prototype of that function is prepended with the keyword "inline". Inline functions are the function where...

4 minutes read.

Selection sort in C

In the C standard, the selection sorting technique exists where the smallest among the unsorted elements of the array is selected at each time and is then inserted into its...

3 minutes read.

Fibonacci Series in C Using For Loop

In this C article, we will let you know about the procedure of displaying the Fibonacci series of the first “n” positive integers. The syntax of for loop used in the...

4 minutes read.

Double Specifier in C

What is a double specifier? The term double denotes the double data type in C. It more accurately depicts floating point numbers. The idea that it has twice the precision of...

3 minutes read.

Two-Dimensional array in C

What is an Array? The collection of a fixed number of elements of homogeneous data types that are stored in contiguous locations in the memory is known as an array. Only...

6 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Prime Number Program in C using for Loop

In this article, we will know about the procedure of checking whether a natural number inputted by the user is a prime number or non-prime number. Definition of the prime number A...

3 minutes read.

Armstrong program in C using function

In this article we will learn how to find Armstrong of a number using function in C. An Armstrong number is a three-digit number that is the sum of its separate...

1 minute read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 minutes read.

Data Types in C

Data type is a very important concept in C programming language. Simply, “A data type is the classification of data values that a data item can have.” We need to...

11 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

Snake Game in C

Snake game in C is basic desktop console program which was created in 1970’s. It is an old classic game which was played by every child across the world. This...

4 minutes read.

Difference between while and do-while loop in C

Introduction Both 'While' and 'Do-While' loops in C mostly have a similar concept, and the code of both loops runs for mainly similar purposes. Both loops process the program/code in the...

3 minutes read.

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.