Working with C-Style Strings

Case-Insensitive C-String Comparison

How can I implement a case-insensitive string comparison using C-style strings?

Abstract art representing computer programming

Implementing a case-insensitive string comparison for C-style strings requires a custom function, as the standard strcmp() is case-sensitive. We'll create a function that compares strings character by character, converting each to lowercase before comparison.

Here's an implementation:

#include <cctype>
#include <cstring>
#include <iostream>

int strcasecmp(const char* s1, const char* s2) {
  while (*s1 && *s2) {
    int diff{
      std::tolower(*s1) - std::tolower(*s2)
    };  
    if (diff != 0) {
      return diff;
    }
    s1++;
    s2++;
  }
  return std::tolower(*s1) - std::tolower(*s2);
}

int main() {
  const char* str1{"Hello"};
  const char* str2{"hElLo"};
  const char* str3{"World"};

  std::cout << "Comparing "
    << str1 << " and " << str2
    << ": " << strcasecmp(str1, str2) << '\n';
  std::cout << "Comparing "
    << str1 << " and " << str3
    << ": " << strcasecmp(str1, str3) << '\n';
}
Comparing Hello and hElLo: 0
Comparing Hello and World: -15

Let's break down the strcasecmp() function:

  1. We use a while loop to iterate through both strings simultaneously.
  2. For each character, we use std::tolower() to convert to lowercase before comparing.
  3. If we find a difference, we return it immediately.
  4. If we reach the end of one or both strings, we compare the last characters (which might be null terminators).

This function returns 0 for equal strings, a negative value if s1 is lexicographically before s2 (ignoring case), and a positive value otherwise.

Note that this implementation is not optimal for large strings or frequent comparisons, as it converts each character to lowercase on every comparison. For better performance in such scenarios, you might want to consider creating lowercase copies of the strings first, or using a lookup table for case conversion.

Also, be aware that this simple implementation doesn't handle locale-specific case conversions. For more complex scenarios involving different languages or Unicode, you'd need to use more sophisticated libraries or techniques.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved