2016-08-02 14 views
-1

私はC#のnoobieです。ContainsKey()bid_amountbid_amountの値でtrueを返さない理由を理解できません。辞書ContainsKey()は文字列の値を比較しません

私は長い文字列("key=value, key=value..."),に分割し、次に=を辞書に作成しました。しかし、私が辞書の中の既知のキーをテストすると、bid_amountは常にfalseを返します。

ContainsKey()を使用して値を比較する方法はありますか? 私は正確に何が欠けていますか?あなたの入力に基づいて

string[] responseStringSplit = responseString.Split (new []{ ',' }); 
Dictionary<string,string> responseDict = new Dictionary<string, string>(); 

foreach (string word in responseStringSplit) 
{ 
    string[] splitString = word.Split (new[]{ ':' }); 
    if (splitString.Length > 1) 
    { 
     responseDict.Add(splitString [0],splitString [1]); 
    } 
    else 
    { 
     Debug.Log ("CouldNotSplit:" + word); 
    } 
} 

foreach (KeyValuePair<string, string> entry in responseDict) 
{ 
    Debug.Log (entry.Key + "=" + entry.Value); 
    if (responseDict.ContainsKey ("bid_amount")) 
    { 
     Debug.Log ("found bid amount"); 
    } 
} 
+2

入力文字列を表示できますか? –

+1

あなたは本当にそのような文字列がありますか?私はそれの周りにスペースがないという意味ですか?おそらく、_spitstring [0]、[1] _ – Steve

+0

Worksの周りにキー/値のペアを追加する前にトリムを追加することができます。あなたの入力を確認してください。有効な入力を持つコードの実際の例はこちらを参照してください。https://dotnetfiddle.net/SxOJ8M –

答えて

0

、あなたの,とあなたのkeyの間のスペースを持っています。あなたの辞書に追加する前に、splitString[0]splitString[1]に.Trim()を呼び出すことを試みてください。

responseDict.Add(splitString[0].Trim(), splitString[1].Trim()); 
+0

はい、末尾にスペースがあり、.Trim()がそれを修正しました。ありがとうございました。 – lawrencehagman

0

あなたは、コード入力を注意深く見ている場合、あなたは2つの問題を抱えて:あなたの入力コードは 『someText、someTextAfterSpace』であるのに対し

  1. あなたによる最初の分割「を、」 - そう」により分割されました、 "そして、あなたがによって分割
  2. 「:」あなたの入力コードがであるのに対し、「=」

コードは次のようになります。

//split by ", " (plus the space) to avoid that problem (or use trim) 
string[] responseStringSplit = responseString.Split (new []{ ", " }); 

//split by "=" instead of current ":" (Or change input string from having '=' to ':') 
string[] splitString = word.Split (new[]{ '=' }); 

をすることを変えるだけでなく、キーはであるためTrim() sおよびToLower()を追加しますホワイトスペースと大文字/小文字の問題を避けるために、もちろん歓迎します

関連する問題