开发者

C#: How to transform String "[['x','x'],['x','x']]" into an Array without Split()ing?

The string looks like a 2-D array:

[['a;b;c','d','e'],['开发者_运维百科a;b;c;d','h','k'], ... ]

But how do i evaluate it and transform it into 2D array in C# without using Split()?


When you have a programming problem and you are stuck, break it down into a simpler programming problem. This answer will show you how to crudely parse using only C# string primitives just one "sub-array" of your string into a list. That would be good progress and then you can start extending and improving the code.

var s = "['a;b;c','d','e']";
List<string> list = new List<string>();
int i = 0;
while (i < s.Length)
{
    char c = s[i++];
    if (c == '[')
    {
        while (i < s.Length)
        {
            c = s[i++];
            if (c == '\'')
            {
                int start = i;
                while (i < s.Length && s[i] != '\'')
                    i++;
                list.Add(s.Substring(start, i - start));
                i++;
            }
            if (i < s.Length && s[i] == ',')
                i++;
            if (i < s.Length && s[i] == ']')
            {
                i++;
                break;
            }
        }
    }
}
foreach (var item in list)
    Console.WriteLine(item);

This produces as output:

a;b;c
d
e

It's not two-dimensional but I'm not going to write your whole program for you. It's also puts it into a List instead of an array, but you have to do that anyway because you don't know how big it is. This is what I mean by breaking the problem down into smaller parts that you can solve.

You can also improve the code by considerable error-checking for missing commas, etc. But this should get you started.


It looks to me like a JSON string. If it is, then use the DataContractJsonSerializer to deserialize the string into a string[][]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜