簡體   English   中英

如何將此字符串拆分為數組?

[英]How to split this string to array?

我有字符串(來自文件):

    [\x22thanh\x22,
        [[\x22thanh\\u003Cb\\u003E nien\\u003C\\/b\\u003E\x22,0,[]],
        [\x22thanh\\u003Cb\\u003E ca\\u003C\\/b\\u003E\x22,0,[]],
        [\x22thanh\\u003Cb\\u003E nhan\\u003C\\/b\\u003E\x22,0,[]],
        [\x22thanh\\u003Cb\\u003E thao\\u003C\\/b\\u003E\x22,0,[]]
    ]

我將此字符串保存到變量名“ s”。 我想在“ [\\ x22”和“ \\ x22”之間分割所有字符串,然后保存到名為“ s2”的數組中。 我該怎么做? 非常感謝你!

您可以執行以下操作:

var myArray = myString.Split("[\x22");

您是否也要刪除最后一個字符?

string[] s2 = s.Split(new string[] {@"[\x22", @"\x22"}, 
                        StringSplitOptions.RemoveEmptyEntries);

您可以找到第一個\\ x22和下一個\\ x22字符串的位置。 接下來,您應該在該位置之間復制文本。 您可以使用IndexOf方法獲取位置。

        string s = @"[\x22thanh\x22,
    [[\x22thanh\\u003Cb\\u003E nien\\u003C\\/b\\u003E\x22,0,[]],
    [\x22thanh\\u003Cb\\u003E ca\\u003C\\/b\\u003E\x22,0,[]],
    [\x22thanh\\u003Cb\\u003E nhan\\u003C\\/b\\u003E\x22,0,[]],
    [\x22thanh\\u003Cb\\u003E thao\\u003C\\/b\\u003E\x22,0,[]]
]";
        string start = @"[\x22";
        string end = @"\x22";
        int pos = -1;

        List<string> list = new List<string>();

        while ((pos = s.IndexOf(start)) > -1)
        {
            s = s.Substring(pos + start.Length);
            if ((pos = s.IndexOf(end)) > -1)
            {
                list.Add(s.Substring(0, pos));
                s = s.Substring(pos + end.Length);
            }
            else
                break;
        }

        string[] s2 = list.ToArray();

編輯

使用Split結果相同:

  string[] s2 = s.Split(new string[] { @"[\x22" }, 
                        StringSplitOptions.RemoveEmptyEntries)
                 .Select(i => i.Substring(0, i.IndexOf(@"\x22")))
                 .ToArray();

暫無
暫無

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

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