How to compare character ignoring case in primitive types
The Character
class of Java API has various functions you can use.
You can convert your char to lowercase at both sides:
Character.toLowerCase(name1.charAt(i)) == Character.toLowerCase(name2.charAt(j))
There are also a methods you can use to verify if the letter is uppercase or lowercase:
Character.isUpperCase('P')
Character.isLowerCase('P')
What is the correct way to compare char ignoring case?
It depends on what you mean by "work for all cultures". Would you want "i" and "I" to be equal even in Turkey?
You could use:
bool equal = char.ToUpperInvariant(x) == char.ToUpperInvariant(y);
... but I'm not sure whether that "works" according to all cultures by your understanding of "works".
Of course you could convert both characters to strings and then perform whatever comparison you want on the strings. Somewhat less efficient, but it does give you all the range of comparisons available in the framework:
bool equal = x.ToString().Equals(y.ToString(),
StringComparison.InvariantCultureIgnoreCase);
For surrogate pairs, a Comparer<char>
isn't going to be feasible anyway, because you don't have a single char
. You could create a Comparer<int>
though.
character array comparison ignoring case
equalsIgnoreCase
is a String
method. You can't apply it on char
s.
You can write
if (!Character.toLowerCase(student[i]) == Character.toLowerCase(correct[i]))
or
if (!Character.toUpperCase(student[i]) == Character.toUpperCase(correct[i]))
What is the best way to compare 2 characters ignoring case in C#?
You can do this:
char c1 = 'a', c2 = 'A';
bool result = String.Equals(c1.ToString(), c2.ToString(), StringComparison.OrdinalIgnoreCase);
How to compare two characters without case sensitivity in C?
You can use low case for both chars, for example by using tolower function:
if (tolower(str1[i])==tolower(str2[j])) printf("Equal");
Also keep in mind: tolower does not work for multibyte char. So for those chars you should use other function
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)
}
How to do case insensitive string comparison?
The simplest way to do it (if you're not worried about special Unicode characters) is to call toUpperCase
:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
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)
Related Topics
How to Pass Parameter from @Url.Action to Controller Function
How to Download Image from Url
How to Remove Empty Lines from a Formatted String
Error: the Entity Type Requires a Primary Key
Select Multiple Fields from List in Linq
How to Rename Keys Within a Json File
How to Iterate Though Each Child Node in an Xml File
Deserialize Multiple Xml Elements With the Same Name Through Xmlserializer Class in C#
Parse Strings to Double With Comma and Point
How to Read Request Body in an ASP.NET Core Webapi Controller
Adding an Incremental Number to Duplicate String
How to Open a Url in Chrome Incognito Mode
Asp.Net Core Form Post Results in a Http 415 Unsupported Media Type Response
How to Authenticate a Webclient Request
Generate C# Class from SQL Server Table Without Store Procedure