簡體   English   中英

如何從哈希集中獲取正確大小寫的值 <string> ?

[英]How do I get the correct-cased value from a hashset<string>?

我有一個使用StringComparer.CurrentCultureIgnoreCase實例化的HashSet<string> ,並且正在廣泛使用.Contains(字符串輸入)來檢查用戶輸入。 如果用戶在錯誤的情況下輸入了一個值,.contains = true,這是正確的,但我還需要更正情況; 如果例如用戶要求輸入myvalueMyValue位於哈希集中,那么最有效的方法還可以返回MyValue以便對用戶的輸入進行大小寫校正?

這是我的意思的粗略代碼示例:

    static HashSet<string> testHS = new HashSet<string>(StringComparer.CurrentCulture);
    static bool InputExists(string input, out string correctedCaseString)
    {
        correctedCaseString = input;
        if (testHS.Contains(input))
        {
            // correctedCaseString = some query result of the cased testHS value?
            return true;
        }
        return false;
    }

您可以使用Dictionary而不是HashSet。 從字符串映射到自身,並使用不區分大小寫的相等比較器(http://msdn.microsoft.com/zh-cn/library/ms132072.aspx)。 然后,您的代碼將變為:

static Dictionary<string, string> testD = new Dictionary<string, string>(StringComparer.CurrentCulture);
static bool InputExists(string input, out string correctedCaseString)
{
    correctedCaseString = input;
    if (testD.ContainsKey(input))
    {
        correctedCaseString = testD[input];
        return true;
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM