safi
safi

Reputation: 3766

string into arrays

i want to put a string into array, suppose i have a string like string a = "dog cat horse mouse" so i want to put this string into an array like a seperate workd as it appear into the string.

string array [0]=dog   
string array [1]=cat   
string array [2]=horse   
string array [3]=mouse

or like this

string array= {"dog", "Cat", "mouse", "horse"};

I want it like this in array, so :)

Upvotes: 1

Views: 185

Answers (6)

Craigt
Craigt

Reputation: 3580

string s = "dog cat horse mouse";
string[] split = s.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

StringSplitOptions.RemoveEmptyEntries will ensure that multiple spaces in the string wont return empty entries after splitting it.

Upvotes: 1

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74340

This should do the job:

string[] array="dog cat horse mouse".Split(new []{' '});

Upvotes: -2

dotbill
dotbill

Reputation: 1001

Here you go...

string a = "dog cat horse mouse"
string[] split = s.Split(" ".ToCharArray());
                //split[0] holds dog
                //split[1] holds cat

Upvotes: 0

John Koerner
John Koerner

Reputation: 38079

You can use the Split method:

        string s = "dog cat horse mouse";
        string[] stringArray = s.Split(' ');
        Console.WriteLine(stringArray[1]);  // cat

Upvotes: 1

Daniel Dinu
Daniel Dinu

Reputation: 1791

You can use String.Split().

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use the Split method:

string a = "dog cat horse mouse";
string[] array = a.Split(' ');

Upvotes: 6

Related Questions