Omar Tantawe
Omar Tantawe

Reputation: 29

How to split a string in to a 2D array row or column?

I have a string which has many line and space.

For example:

string lines = "my name is omar\nliving in whateverf\ng i j";

I need to split it into a 2D array in which every word is in an index and each row represents a line.

Which means the 2D array should be more like this:

my      name  is omar
living  in    whatever
g       i     j

Is it possible?

I have tried splitting it first to lines and then spiting it to words, but I need id in a 2d array

string [] l = lines.split('\n');

for(int i = 0; i < l.length; i++)
{
     string [] oneLine= l[i].split(' ');
     //and put the rest of the code here
}

Upvotes: 1

Views: 743

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

Here is how you can have an array or arrays (string[][]):

 var results = z.Split(Environment.NewLine.ToArray()).Select(a => a.Split(' ')).ToArray();

If you still want to convert it to 2D array (string[,]) you can do it as described here.

Upvotes: 2

Jeffin Sam
Jeffin Sam

Reputation: 118

   l=string.split('\n')
   for i in range(0,len(l)):
        l[i]=l[i].split(" ")
    print(l) 

Split the string on basis of \n and then do again on each basis of word

Upvotes: 0

Related Questions