2011-01-17 6 views
5

私が使用しているAPIの関数の1つは、基本的には大文字のブロックを返し、セミコロンで各キー/値を区切ります。どのようにC#でこのようなテキストを解析するのですか?C#テキストのブロックのブロック

結果=成功; income_today =; income_thismonth =; income_thisyear =; orders_pending = 19; orders_today_cancelled = 0; orders_today_pending = 0; orders_today_fraud = 0; orders_today_active = 0; orders_today_total = 0; orders_yesterday_cancelled = 0; orders_yesterday_pending = 3 ; orders_yesterday_fraud = 2; orders_yesterday_active = 0;

答えて

13

の場合のように見えるまあ、:キーと値のペアにブロックを分割する

  • コールtext.Split(';')キーと値
に分割するために、各ペアの
  • コールpair.Split('=')

    string.Splitには、さまざまなオーバーロードがあります。空の値などを抑制するかどうかにかかわらず、返す文字列の数を調べたい場合があります。

  • +0

    ありがとうございました! –

    +0

    私は1896ブロンズのバッジをお渡しします;) – Arcturus

    +0

    ハハありがとう:Pまた、これについては右ですか? http://www.ampaste.net/d5fb70b78私がlistBox1.Items.Add(stat)を実行するとき。それはキー/値の罰金を印刷しますが、私がlistBox1.Items.Add(値)を実行すると、それは "String [] Array"をリストボックスに追加します。 –

    0

    String.Split(Char[])を使用します。あなたが必要とする例を適用するstring [] split = words.Split(new Char [] {';'});

    +0

    "新しい文字列を明示的に書く必要はありません[] {} "パラメーターの一部はパラメーター配列(params)です。 –

    +0

    ああ、配列が1つの要素の文字列である場合、私はそう参照してください[] split = words.Split( ';');十分であろう? –

    1

    私は最近同様の問題を抱えていました。ここにあなたの役に立つコードがあります。戦略はJon Skeet's anwersと同じです。

    これは、キーがテキストのあなたのブロックに一意であるように見えます、したがって、あなたはDictionary

    string[] pairs = block.Split(';'); 
    Dictionary<string, string> values = new Dictionary<string, string>(); 
    
    foreach (var element in pairs) 
    { 
        var tmp = element.Split('='); 
        var key = tmp[0]; 
        var val = tmp.Length == 2 ? tmp[1] : string.Empty; 
        values.Add(key,val); 
    } 
    
    foreach (var el in values) 
    { 
        Console.WriteLine(el); 
    } 
    
    +0

    それは美しく働いた、ありがとう! –

    1

    を使用して、ここに(明確にするため、複数行にわたって書式設定)ワンライナーだことがあります。

    Dictionary<string, string> dictionary = raw 
        .Split(new [] { ';', }, StringSplitOptions.RemoveEmptyEntries) 
        .Select(x => x.Split('=')) 
        .ToDictionary(x => x[0], x => x[1]);