[英]What is the correct way to compare char ignoring case?
我想知道比較兩個忽略大小寫的字符的正確方法適用於所有文化。 另外, Comparer<char>.Default
是在不忽略大小寫的情況下測試兩個字符的最佳方法嗎? 這對代理對有效嗎?
編輯:添加示例IComparer<char>
實現
如果這對任何人都有幫助,這就是我決定使用的
public class CaseInsensitiveCharComparer : IComparer<char> {
private readonly System.Globalization.CultureInfo ci;
public CaseInsensitiveCharComparer(System.Globalization.CultureInfo ci) {
this.ci = ci;
}
public CaseInsensitiveCharComparer()
: this(System.Globalization.CultureInfo.CurrentCulture) { }
public int Compare(char x, char y) {
return Char.ToUpper(x, ci) - Char.ToUpper(y, ci);
}
}
// Prints 3
Console.WriteLine("This is a test".CountChars('t', new CaseInsensitiveCharComparer()));
這取決於您所說的“為所有文化工作”是什么意思。 即使在土耳其,您也希望“我”和“我”平等嗎?
你可以使用:
bool equal = char.ToUpperInvariant(x) == char.ToUpperInvariant(y);
...但我不確定根據您對“作品”的理解,根據所有文化,這是否“有效”。
當然,您可以將兩個字符都轉換為字符串,然后對字符串執行任何您想要的比較。 效率稍低,但它確實為您提供了框架中可用的所有比較范圍:
bool equal = x.ToString().Equals(y.ToString(),
StringComparison.InvariantCultureIgnoreCase);
對於代理對, Comparer<char>
無論如何都不可行,因為您沒有單個char
。 不過,您可以創建一個Comparer<int>
。
使用默認的( 不是不變的)區域性:
if (char.ToLower(ch1) == char.ToLower(ch2))
{ .... }
或指定一種文化:
CultureInfo myCulture = ...;
if (char.ToLower(ch1, myCulture) == char.ToLower(ch2, myCulture))
{ .... }
據我了解,沒有真正的方法可以“適用於所有文化”。 要么您想出於某種內部的、非向用戶顯示的原因(在這種情況下您應該使用 InvariantCulture)來比較字符,要么您想使用用戶的 CurrentCulture。 顯然,使用用戶當前的文化意味着您將在不同的語言環境中獲得不同的結果,但它們將與您在這些語言環境中的用戶期望的結果一致。
如果不了解您為什么要比較兩個字符的更多信息,我無法真正建議您應該使用哪個字符。
我建議比較大寫,如果它們不匹配,則比較小寫,以防語言環境的大寫和小寫邏輯的行為略有不同。
附錄
例如,
int CompareChar(char c1, char c2)
{
int dif;
dif = char.ToUpper(c1) - char.ToUpper(c2);
if (diff != 0)
dif = char.ToLower(c1) - char.ToLower(c2);
return dif;
}
我認為在運行時可用的內容類似於以下內容
public class CaseInsensitiveCharComparer : IComparer<char> {
private readonly System.Globalization.CultureInfo ci;
public CaseInsensitiveCharComparer(System.Globalization.CultureInfo ci) {
this.ci = ci;
}
public CaseInsensitiveCharComparer()
: this(System.Globalization.CultureInfo.CurrentCulture) { }
public int Compare(char x, char y) {
return Char.ToUpper(x, ci) - Char.ToUpper(y, ci);
}
}
// Prints 3
Console.WriteLine("This is a test".CountChars('t', new CaseInsensitiveCharComparer()));
string.Compare("string a","STRING A",true)
它適用於每個字符串
你可以試試:
class Test{
static int Compare(char t, char p){
return string.Compare(t.ToString(), p.ToString(), StringComparison.CurrentCultureIgnoreCase);
}
}
但我懷疑這是做到這一點的“最佳”方式,但我並不是您需要檢查的所有情況......
我知道這是一個舊帖子,但從那時起事情發生了變化。
可以通過使用擴展來回答上述問題。 這將擴展 char.Equals 以允許局部性和不區分大小寫。
在擴展類中,添加如下內容:
internal static Boolean Equals(this Char src, Char ch, StringComparison comp)
{
Return $"{src}".Equals($"{ch}", comp);
}
我目前正在工作,所以無法檢查這個,但它應該可以工作。
安迪
您可以為 caseInsensetive 匹配提供最后一個參數為真
string.Compare(lowerCase, upperCase, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.