2
3

More than 5 years have passed since last update.

csharp > .Split で複数のデリミタを使う > string separator = ",{:}"; / .Split(separator.ToCharArray()))

Last updated at Posted at 2015-09-23

JSON文字列を単純に要素だけ取り出したい。

try1

',', '{', ':', '}'をデリミタとしたい時は参考ページによると、以下のようにすればいいようだ。

.Split(new char [] {',', '{', ':', '}'})

ideoneで実装した。

using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        string sample = "{\"AAA\":{\"bbb\",\"ccc\"},\"ddd\"";
        foreach(var element in sample.Split(new char [] {',', '{', ':', '}'})) {
            if (element.Length > 0) {
                Console.WriteLine(element);
            }
        }
    }
}
結果
Success time: 0.03 memory: 23880 signal:0
"AAA"
"bbb"
"ccc"
"ddd"

improved (by muroさん)

コメントにて @muro さんから教えていただいた、string型のseparatorに文字を格納しておき、.ToCharArray()を使ってSplitを組み合わせる方法の方がコードリーディングがはるかにしやすい。

また、separatorをstring型にすることで、後で変更したりもできそうという点もいい。

実際のコードはmuroさんのコメント参照。

ideoneでも動作確認済。
http://ideone.com/hB38Yg

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3