• strcmp() function

    Welcome to another blog post where we explore the world of C programming! In this article, we will be discussing the strcmp() function in C. If you are familiar with string comparisons and want to dive deeper into this topic, or if you are new to C programming and want to learn how to compare strings efficiently, then you’re in the right place. So, let’s get started!

    Introduction

    Comparing strings is a common operation in programming. Whether you want to check if two strings are equal or determine the lexicographical order of two strings, the strcmp() function in C comes to your rescue. C is a low-level programming language known for its efficiency and simplicity, and the strcmp() function plays a crucial role in string manipulation.

    The strcmp() function is part of the string.h library in C, which provides a set of functions for manipulating C strings. This function compares two strings and returns an integer value indicating their relationship.

    The syntax of strcmp()

    The syntax of the strcmp() function is relatively straightforward:

    int strcmp(const char *str1, const char *str2);

    Here, str1 and str2 are the two strings to be compared. The function returns an integer value based on the comparison result. The possible return values are:

    • 0: Both strings are equal.

    • A negative value: The ASCII value of the first unmatched character in str1 is less than the ASCII value of the corresponding character in str2.

    • A positive value: The ASCII value of the first unmatched character in str1 is greater than the ASCII value of the corresponding character in str2.

    Let’s take a closer look at how the strcmp() function works and explore some examples.


    Understanding the return values

    To better understand the return values of the strcmp() function, let’s take a look at some examples:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[] = "apple";
        char str2[] = "banana";
      
        int result = strcmp(str1, str2);
      
        if (result == 0) {
            printf("The strings are equal.\n");
        } else if (result > 0) {
            printf("str1 is greater than str2.\n");
        } else {
            printf("str2 is greater than str1.\n");
        }
      
        return 0;
    }

    In this example, we compare the strings “apple” and “banana” using the strcmp() function. Since the ASCII value of ‘a’ (97) is less than the ASCII value of ‘b’ (98), the return value is negative. Hence, the output will be:

    str2 is greater than str1.

    Comparing strings lexicographically

    The strcmp() function performs lexicographical comparison of two strings. This means that it compares strings character by character based on their ASCII values. The comparison stops as soon as a mismatch is found or one of the strings ends. Let’s see some examples to understand this better:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[] = "apple";
        char str2[] = "application";
      
        int result = strcmp(str1, str2);
      
        if (result == 0) {
            printf("The strings are equal.\n");
        } else if (result > 0) {
            printf("str1 is greater than str2.\n");
        } else {
            printf("str2 is greater than str1.\n");
        }
      
        return 0;
    }

    In this example, we compare the strings “apple” and “application”. Since the first five characters in both strings are the same, the comparison stops at ‘e’ which has an ASCII value of 101, while the corresponding character in the second string is ‘i’ with an ASCII value of 105. Therefore, the return value is negative, and the output will be:

    str2 is greater than str1.

    Case sensitivity

    One important thing to note is that the strcmp() function is case-sensitive. This means that uppercase letters are considered different from lowercase letters. Let’s take a look at an example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[] = "apple";
        char str2[] = "Apple";
      
        int result = strcmp(str1, str2);
      
        if (result == 0) {
            printf("The strings are equal.\n");
        } else if (result > 0) {
            printf("str1 is greater than str2.\n");
        } else {
            printf("str2 is greater than str1.\n");
        }
      
        return 0;
    }

    In this example, we compare the strings “apple” and “Apple”. Since ‘a’ and ‘A’ have different ASCII values, the return value will be negative, and the output will be:

    str2 is greater than str1.

    If you want to perform a case-insensitive comparison, you can use the strcasecmp() function available in some C libraries.


    Practical applications

    The strcmp() function is widely used in various scenarios, ranging from simple string comparisons to more complex operations. Let’s explore some practical applications where the strcmp() function can be handy.

    Sorting strings

    One common use case of the strcmp() function is to sort a list of strings. By comparing each string with its neighboring strings and swapping them when necessary, you can achieve a lexicographically sorted list. Here’s an example:

    #include <stdio.h>
    #include <string.h>
    
    void bubbleSort(char *arr[], int size) {
        int i, j;
        char *temp;
    
        for (i = 0; i < size - 1; i++) {
            for (j = 0; j < size - i - 1; j++) {
                if (strcmp(arr[j], arr[j + 1]) > 0) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    int main() {
        char *fruits[] = {"banana", "pear", "apple", "orange"};
        int size = sizeof(fruits) / sizeof(fruits[0]);
      
        bubbleSort(fruits, size);
      
        printf("Sorted list of fruits:\n");
        for (int i = 0; i < size; i++) {
            printf("%s\n", fruits[i]);
        }
      
        return 0;
    }

    In this example, we use the bubble sort algorithm to sort an array of strings in lexicographical order. The strcmp() function is used to compare each element with its neighboring element, and the strings are swapped when necessary.

    Searching for a string in a list

    Another useful application is searching for a particular string in a list. By comparing each string in the list with the target string using the strcmp() function, you can determine if the string exists or not. Here’s an example:

    #include <stdio.h>
    #include <string.h>
    
    int search(char *arr[], int size, char *target) {
        for (int i = 0; i < size; i++) {
            if (strcmp(arr[i], target) == 0) {
                return i;
            }
        }
      
        return -1;
    }
    
    int main() {
        char *fruits[] = {"banana", "pear", "apple", "orange"};
        int size = sizeof(fruits) / sizeof(fruits[0]);
        char *target = "pear";
      
        int index = search(fruits, size, target);
      
        if (index != -1) {
            printf("The target string exists at index %d.\n", index);
        } else {
            printf("The target string does not exist in the list.\n");
        }
      
        return 0;
    }

    In this example, we search for the string “pear” in an array of fruits. Because the strcmp() function returns 0 when it finds the target string, we can use it to determine whether the string exists in the array or not.


    Conclusion

    In this blog post, we have explored the strcmp() function in C. We have learned about its syntax, return values, and how it performs lexicographical comparison of strings. We have also observed practical applications where people can use the function, such as sorting strings and performing string searches within a list.

    The strcmp() function is a powerful tool in C programming when it comes to string manipulation and comparison. By understanding how to use this function effectively, you can write more efficient and reliable programs.

    I encourage you to explore more string manipulation functions or deepen your knowledge of C programming by checking out the C documentation or exploring online resources dedicated to C programming.

    Keep coding, keep learning, and don’t hesitate to share your newfound knowledge with others. Happy programming!