在C#中将字符串拆分为字符串数组

时间:2018-09-24 19:04:45

标签: c# split

如何将字符串拆分为字符串数组。

我的字符串看起来像这样

string orgString = "1234-|@$@|-George,Michael -$@%@$-65489-|@$@|-Lawrence,  Steve J  -$@%@$-7897954-|@$@|-Oliver Mike  -$@%@$-56465-|@$@|-Waldimir Tursoky";

现在我希望我的字符串数组与-|@$@|-一起存储名称和数字

我尝试了以下代码

string[] strArray = orgString.Split(new string[] {"-$@%@$-"}, StringSplitOptions.RemoveEmptyEntries);

我的输出如下:

"1234-|@$@|-George,Michael "

但是我想要的输出是(名字在前,数字在后)

"George,Michael -|@$@|-1234"

我如何在C#中实现这一目标?

2 个答案:

答案 0 :(得分:2)

只需交换结果字符串中的部分即可:

string orgString = "1234-|@$@|-George,Michael -$@%@$-65489-|@$@|-Lawrence,  Steve J  -$@%@$-7897954-|@$@|-Oliver Mike  -$@%@$-56465-|@$@|-Waldimir Tursoky";
string[] resultingList = orgString.Split(new string[] {"-$@%@$-"}, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Split(new string[] {"-|@$@|-"}, StringSplitOptions.RemoveEmptyEntries).Aggregate((x11,y)=>{return y+" -|@$@|- "+x11;})).ToArray();
foreach(string result in resultingList)
{
    Console.WriteLine(result);
}

答案 1 :(得分:1)

您可以再次拆分然后重新组合

string outerDivider = "-$@%@$-";
string innerDivider = "-|@$@|-";

var results = orgString
    // Split by outer divider
    .Split(new string[] { outerDivider }, StringSplitOptions.RemoveEmptyEntries)
    // Then for each of the results, split again on the inner divider
    .Select(x => x.Split(new string[] { innerDivider }, StringSplitOptions.RemoveEmptyEntries))
    // Swap the order of elements around the inner divider and recombine into a string
    .Select(x => string.Join(innerDivider, x[1], x[0]));