简体   繁体   English

如何将此字符串拆分为数组?

[英]How to split this string to array?

I have string (from a file): 我有字符串(来自文件):

    [\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,[]]
    ]

I saved this string to a variable name "s". 我将此字符串保存到变量名“ s”。 I want split all strings betwen "[\\x22" and "\\x22," then save to an array named "s2". 我想在“ [\\ x22”和“ \\ x22”之间分割所有字符串,然后保存到名为“ s2”的数组中。 How I can do this? 我该怎么做? Thank you very much! 非常感谢你!

You can do as following : 您可以执行以下操作:

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

Do you want to remove the last characters aswell? 您是否也要删除最后一个字符?

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

You can find the position of first \\x22 and next \\x22 string. 您可以找到第一个\\ x22和下一个\\ x22字符串的位置。 Next, you should copy the text beetween that position. 接下来,您应该在该位置之间复制文本。 You can get position using IndexOf method. 您可以使用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();

EDIT 编辑

Same result using Split : 使用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