开发者

Split string by array of strings and preserve delimeters

I have something like this:

  string[] names= {"john","joe", "jim"};
  data="john,4,3,6,joe,3,6,2,jim,3,6,7";
  string[] results=data.Split(names,StringSplitOptions.RemoveEmptyEntries);

this gives:

 ,4,3,6

 ,3,6,2

 ,3,6,7

but i want the names to be in the results array a开发者_StackOverflows well.


How about adding this line at the end:

results = results.Select((x, i) => names[i] + x).ToArray();

This will prepend the name in front of each entry, outputting:

john,4,3,6
joe,3,6,2
jim,3,6,7


You could keep your original code, then zip in the names:

string[] names= new [] {"john","joe", "jim" };
string data="john,4,3,6,joe,3,6,2,jim,3,6,7";
string[] results = data.Split(names, StringSplitOptions.RemoveEmptyEntries)
                       .Zip(names, (values, name) => name + values)
                       .ToArray();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜