×

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

Decimal to Hexadecimal in C

Decimal to Hexadecimal in C Let us first understand the definitions of decimal and hexadecimal. In algebra, a decimal number is defined as a number whose whole number part and a...

3 minutes read.

Local Labels in C

Anyone who has written programs in the C programming language is required to be familiar with the "go to" and "labels" used in C to navigate between functions. "Local labels"...

4 minutes read.

Bitwise XOR Operator in C

What is Bitwise? As we know, bits are the smallest unit of a number and are mostly used in a computing system. So, in bitwise, we do operations on bits instead...

3 minutes read.

Caesar Cipher Program in C

What is Caesar Cipher? The Caesar Cipher is a type of substitution cipher that is named after Julius Caesar, who is said to have used it to encrypt messages sent to...

2 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

Format Specifier in C

Format Specifier in C Format specifiers can be described as an operator that is used to print the data referred by any object or variable in combination with the printf ()...

3 minutes read.

While Loop in C programming examples

Introduction There is always a header file containing all the essential data regarding inputs and outputs of various functions in the C programs. The following statement describes how to use/add header file...

22 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Heap Sort in C

In this tutorial, we will learn about heap sorting in C language, but before going to Heap sort, we have to know the concept of Complete Binary Tree. What is Complete...

8 minutes read.

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

How to install a C compiler in windows 10-64bit

Many C compilers can be installed on your pc. The most downloaded compilers include GCC, Turbo C++, Visual Studio, etc. This article includes the installation of the Turbo C++ compiler in...

6 minutes read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

Use of free() function in C

Introduction The free() function uses in C programming language. The free() function in the C programming language uses to release or deallocate the memory blocks; these blocks are previously allocated by calloc(), malloc() or realloc()...

3 minutes read.

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

Pointer in C

Pointer is a variable that is used to contain the address of another variable. We can easily create a pointer in C language. Example: int *ptr Symbol Description & (ampersand sign) Address of an operator...

1 minute read.

Fibonacci series in C

We have learned about the Fibonacci series in mathematics. For a quick recap, A Fibonacci series is the sequence of numbers following a certain pattern i.e., the next number should...

3 minutes read.

Call by Value and Call by Reference in C

Call by reference and call by value are two different ways of passing arguments to a function in C programming language. Call by reference means that the called function is...

4 minutes read.