How to Compare Strings Ignoring the Case

Comparing two strings, ignoring case in C#

The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.

Best way to compare two strings ignoring case

If you have a look at the corresponding reference sources

https://referencesource.microsoft.com/#mscorlib/system/string.cs,bda3b2c94b5251ce

    public static int Compare(String strA, String strB, bool ignoreCase)
{
if (ignoreCase) {
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
}
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
}

https://referencesource.microsoft.com/#mscorlib/system/string.cs,0be9474bc8e160b6

    public static int Compare(String strA, String strB, StringComparison comparisonType) 
{
...
// Agrument validation, reference equality, null test

switch (comparisonType) {
...
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);

https://referencesource.microsoft.com/#mscorlib/system/string.cs,d47c1f57ad1e1e6e

    public static bool Equals(String a, String b, StringComparison comparisonType) {
...
// Agrument validation, reference equality, null test

switch (comparisonType) {
...
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);

you'll find these three methods being equal one another. As for other ways, Regex.IsMatch is definitely an overshoot (all you have to do is to compare strings); ToLower() can be tricky when dealing with culture specific letters, see

https://en.wikipedia.org/wiki/Dotted_and_dotless_I

that's why a better design is to declare your intends clearly (= I want to compare strings) then mask them (and let the system decieve you)

How do I do a case-insensitive string comparison?

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")

As of Python 3.3, casefold() is a better alternative:

string1 = 'Hello'
string2 = 'hello'

if string1.casefold() == string2.casefold():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")

If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.

How to compare strings ignoring the case

You're looking for casecmp. It returns 0 if two strings are equal, case-insensitively.

str1.casecmp(str2) == 0

"Apple".casecmp("APPLE") == 0
#=> true

Alternatively, you can convert both strings to lower case (str.downcase) and compare for equality.

How to ignore case in string comparison

You can just use the LCase function:

If LCase([G56]) = "not applicable" Then

How to compare two strings ignoring case in Swift language?

Try this:

var a = "Cash"
var b = "cash"
let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)

// You can also ignore last two parameters(thanks 0x7fffffff)
//let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch)

result is type of NSComparisonResult enum:

enum NSComparisonResult : Int {

case OrderedAscending
case OrderedSame
case OrderedDescending
}

So you can use if statement:

if result == .OrderedSame {
println("equal")
} else {
println("not equal")
}

Ignore case in string comparison

This is the most pythonic I can think of. Better to ask for foregiveness than for permission:

>>> def iequal(a, b):
... try:
... return a.upper() == b.upper()
... except AttributeError:
... return a == b
...
>>>
>>> iequal(2, 2)
True
>>> iequal(4, 2)
False
>>> iequal("joe", "Joe")
True
>>> iequal("joe", "Joel")
False

Ignore case and compare in C#

use this:

var result = String.Compare("AA", "aa", StringComparison.OrdinalIgnoreCase);

String.Compare Method (String, String, Boolean)

What is an efficient way to compare strings while ignoring case?

There is no built-in method, but you can write one to do exactly as you described, assuming you only care about ASCII input.

use itertools::{EitherOrBoth::*, Itertools as _}; // 0.9.0
use std::cmp::Ordering;

fn cmp_ignore_case_ascii(a: &str, b: &str) -> Ordering {
a.bytes()
.zip_longest(b.bytes())
.map(|ab| match ab {
Left(_) => Ordering::Greater,
Right(_) => Ordering::Less,
Both(a, b) => a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase()),
})
.find(|&ordering| ordering != Ordering::Equal)
.unwrap_or(Ordering::Equal)
}

As some comments below have pointed out, case-insensitive comparison is not going to work properly for UTF-8, without operating on the whole string, and even then there are multiple representations of some case conversions, which could give unexpected results.

With those caveats, the following will work for a lot of extra cases compared with the ASCII version above (e.g. most accented Latin characters) and may be satisfactory, depending on your requirements:

fn cmp_ignore_case_utf8(a: &str, b: &str) -> Ordering {
a.chars()
.flat_map(char::to_lowercase)
.zip_longest(b.chars().flat_map(char::to_lowercase))
.map(|ab| match ab {
Left(_) => Ordering::Greater,
Right(_) => Ordering::Less,
Both(a, b) => a.cmp(&b),
})
.find(|&ordering| ordering != Ordering::Equal)
.unwrap_or(Ordering::Equal)
}


Related Topics



Leave a reply



Submit