• C Program to Compare String without using strcmp()

    In the world of programming, string comparison is a common task that arises in various scenarios. Whether you’re working with names, addresses, or any other textual data, being able to compare strings accurately is fundamental. In C programming, the strcmp() function is commonly used to compare strings. However, there are occasions when you might need to compare strings without using this built-in function. In this blog post, we’ll explore how to accomplish that.

    Understanding String Comparison

    Before we delve into the process of comparing strings without strcmp(), it’s important to understand how string comparison works in C. Strings in C are essentially arrays of characters, terminated by a null character ‘\0’. When comparing two strings, the characters at each index are compared until a difference is encountered. The comparison is based on the ASCII values of the characters.

    To compare strings, we typically use the strcmp() function, which returns 0 if the strings are equal, a negative value if the first string is less than the second, and a positive value if the first string is greater than the second. However, our goal here is to achieve the same result without using this built-in function.


    Comparing Strings without strcmp()

    To compare strings without using strcmp(), we can implement our own custom function. Let’s call it my_strcmp(). Essentially, this function will iterate through the characters of both strings and make a comparison.

    #include <stdio.h>
    
    int my_strcmp(const char* str1, const char* str2) {
        while (*str1 != '\0' || *str2 != '\0') {
            if (*str1 < *str2) {
                return -1;
            } else if (*str1 > *str2) {
                return 1;
            }
            str1++;
            str2++;
        }
        return 0;
    }
    
    int main() {
        char string1[] = "Hello";
        char string2[] = "Hello";
    
        int result = my_strcmp(string1, string2);
        if (result == 0) {
            printf("The strings are equal.\n");
        } else if (result < 0) {
            printf("String 1 is less than String 2.\n");
        } else {
            printf("String 1 is greater than String 2.\n");
        }
    
        return 0;
    }

    In this example, we define the my_strcmp() function, which takes two const char pointers, str1 and str2, as parameters. Inside the function, we initialize a while loop that continues until both strings reach the null character (‘\0’). Within the loop, we compare each character using the ASCII values. If str1 is smaller than str2, we return -1, indicating that str1 is less than str2. Conversely, if str1 is greater than str2, we return 1. Finally, if both strings are equal, we return 0.

    In the main() function, we create two example strings, string1 and string2, and then call the my_strcmp() function to compare them. Based on the result, we print an appropriate message.


    Enhancing the String Comparison Function

    The my_strcmp() function we just implemented is a basic version of string comparison without using the strcmp() function. However, we can enhance it further to handle different scenarios.

    Making it Case-insensitive

    By default, the comparison of characters in our my_strcmp() function is case-sensitive. This means that ‘A’ and ‘a’ are considered different. To make the function case-insensitive, we can modify it as follows:

    int my_strcmp(const char* str1, const char* str2) {
        while (*str1 != '\0' || *str2 != '\0') {
            if (tolower(*str1) < tolower(*str2)) {
                return -1;
            } else if (tolower(*str1) > tolower(*str2)) {
                return 1;
            }
            str1++;
            str2++;
        }
        return 0;
    }

    In this updated version, we use the tolower() function to convert each character to lowercase before making the comparison. This ensures that ‘A’ and ‘a’ are considered equal.

    Handling Strings of Different Lengths

    The current implementation of my_strcmp() assumes that both strings have the same length. To handle strings of different lengths, we can modify the function as follows:

    int my_strcmp(const char* str1, const char* str2) {
        while (*str1 != '\0' || *str2 != '\0') {
            if (*str1 == '\0' && *str2 != '\0') {
                return -1;
            } else if (*str2 == '\0' && *str1 != '\0') {
                return 1;
            } else if (*str1 < *str2) {
                return -1;
            } else if (*str1 > *str2) {
                return 1;
            }
            str1++;
            str2++;
        }
        return 0;
    }

    In this updated version, we handle the case where one string is shorter than the other. If str1 reaches the null character first, it means str1 is shorter. In this case, we return -1. Similarly, if str2 reaches the null character first, we return 1. These modifications allow our function to handle strings of different lengths correctly.


    Putting it into Practice

    Now that we have our custom string comparison function, it’s time to put it into practice. Let’s consider a scenario where we need to compare the names of students in a class. We can create an array of strings representing the names and implement a function to find a specific name within the array. Here’s an example:

    #include <stdio.h>
    
    int findStudent(const char* name, const char* students[], int size) {
        for (int i = 0; i < size; i++) {
            if (my_strcmp(name, students[i]) == 0) {
                return i;
            }
        }
        return -1;
    }
    
    int main() {
        char* students[] = {"Alice", "Bob", "Charlie", "David", "Eve"};
        char* name = "David";
    
        int index = findStudent(name, students, sizeof(students)/sizeof(students[0]));
        if (index >= 0) {
            printf("%s is found at index %d.\n", name, index);
        } else {
            printf("%s is not found.\n", name);
        }
    
        return 0;
    }

    In this example, we define an array of student names using char pointers. We also define a function named findStudent() that takes the name to search for, the array of student names, and the size of the array as parameters. Inside the function, we use a for loop to iterate through each name in the array. For each name, we call our custom string comparison function, my_strcmp(), to check if it matches the name we’re searching for. If we find a match, we return the index at which we found the name. If we don’t find a match, we return -1.

    In the main() function, we create an example name to search for (“David”) and call the findStudent() function. If the name is found, we print a message indicating the index at which the name is found. Otherwise, we print a message indicating that the name is not found.


    Conclusion

    In this blog post, we explored how to compare strings in C without using the built-in strcmp() function. We implemented our own custom string comparison function, my_strcmp(), which enables us to compare strings accurately. We also enhanced the function to make it case-insensitive and handle strings of different lengths.

    By understanding the underlying ASCII values of characters and leveraging the power of loops and conditionals, we can accomplish complex tasks like string comparison. Custom string comparison functions come in handy when you want to tailor the comparison logic to suit specific requirements.

    Now that you’ve learned how to compare strings without using strcmp(), you can apply this knowledge to various programming scenarios. Whether you’re building text-based games, implementing search algorithms, or working with any type of textual data, string comparison is always a fundamental aspect to consider.

    Keep exploring and experimenting with string comparison in C, and you’ll deepen your understanding of this essential programming concept. Happy coding!