简体   繁体   中英

what is the best way to split string in c#

i have a string that look like that "a,b,c,d,e,1,4,3,5,8,7,5,1,2,6.... and so on. i am looking for the best way to split it and make it look like that:

abcde

1 4 3 5 8

7 5 1 2 6

thanks in advanced

Assuming, that you have a fix number of columns (5):

string Input = "a,b,c,d,e,11,45,34,33,79,65,75,12,2,6";
int i = 0;
string[][] Result = Input.Split(',').GroupBy(s => i++/5).Select(g => g.ToArray()).ToArray();

First I split the string by , character, then i group the result into chunks of 5 items and select those chunks into arrays.

Result:

a    b    c    d    e
11   45   34  33   79
65   75   12   2    6

to write that result into a file you have to

using (System.IO.StreamWriter writer =new System.IO.StreamWriter(path,false))
{
    foreach (string[] line in Result)
    {
        writer.WriteLine(string.Join("\t", line)); 
    }
}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM