Click here to Skip to main content
15,909,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have data in a text:

W S 6
W H 11
W D 6
W C 8
W N 9

N S 7
N H 2
N D 6
N C 5

N N 4
E S 6
E H 11
E D 6
E C 8
E N 9


and I want to split them to a string array like:
string[0] array=
W S 6
W H 11
W D 6
W C 8
W N 9

string[1] array=
N S 7
N H 2
N D 6
N C 5

string[2] array=
N N 4
E S 6
E H 11
E D 6
E C 8
E N 9


What I have tried:

I had been do:
using(StreamReader reader = new StreamReader(uploadedFile.InputStream))
                {
                   
                    string read = reader.ReadToEnd();
                    string[] Array = Regex.Split(read,"\n");
                }


But It cannot done, Pleas help me.
Posted
Updated 13-Jul-17 13:56pm
v3

Use string.Split

String.Split Method (String[], StringSplitOptions) (System)[^]

string[] x = text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);


If you have multiple lines you might need to split on the new line then go through each line and split on the space. Or just read the data line by line and split on space rather than reading it in one chunk.
 
Share this answer
 
It is assumed that your text uses \n as line break.
var text = "W S 6\nW H 11\nW D 6\nW C 8\nW N 9\n\nN S 7\nN H 2\nN D 6\nN C 5\n\nN N 4\nE S 6\nE H 11\nE D 6\nE C 8\nE N 9\n";

Then you could split this text like this:
var array = Regex.Split(text, "\n\n");
 
Share this answer
 
Splitting with a Regex.Split is kinda overkill when you want to split by 1 char. Try var array = read.Split('\n');.

Beware of '\r' as it can sometime accompany \n depending on the source of the string. It might be an idea to trim the strings once split. Linq would be easiers:

C#
using(StreamReader reader = new StreamReader(uploadedFile.InputStream))
    {
        string read = reader.ReadToEnd();
        string[] Array = read.Split(read,"\n").Select(s=>s.Trim({' ','\r'}).ToArray();
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900