darkniz
darkniz

Reputation: 13

Split string array into smaller arrays

I've looked around but can't find anything that has helped me. I have the following issue - I have a string array that contains:

[0] = "2.4 kWh @ 105.00 c/kWh"

where [0] is the index of the array. I need to split it by a space, so that I can have several smaller arrays. So it should look like:

[0] will contain 2.4
[1] will contain kWh
[2] will contain @
[3] will contain 105.00
[4] will contain c/mWh

I've tried several solutions but none works. Any assistance would be highly appreciated.

Upvotes: 0

Views: 174

Answers (3)

w.b
w.b

Reputation: 11228

This will give you a two dimensional array (array of string arrays):

var newArr = strArr.Select(s => s.Split(' ').ToArray()).ToArray();

for example:

string[] strArr = new string[] { "2.4 kWh @ 105.00 c/kWh", "Hello, world" };

var newArr = strArr.Select(s => s.Split(' ').ToArray()).ToArray();

for (int i = 0; i < newArr.Length; i++)
{
    for(int j = 0; j < newArr[i].Length; j++)
        Console.WriteLine(newArr[i][j]);
    Console.WriteLine();
}

//  2.4
//  c/kWh
//  @
//  105.00
//  kWh
//
//  Hello,
//  world

Upvotes: 0

Naveen Kumar Alone
Naveen Kumar Alone

Reputation: 7668

Reference

string s = "2.4 kWh @ 105.00 c/kWh";
string[] words = s.Split(new char [] {' '});  // Split string on spaces.
foreach (string word in words)
{
    Console.WriteLine(word);
}

Then you can get the console output as

2.4
kWh
@
105.00
c/mWh

Upvotes: 3

Matthew Haugen
Matthew Haugen

Reputation: 13286

We'll use string[] strings = new[] { "2.4 kWh @ 105.00 c/kWh", "this is a test" }; as an example of your array.

This is how you can put it all into one array. I've kept it as an IEnumerable<T> to keep that benefit, but feel free to append .ToArray().

public IEnumerable<string> SplitAll(IEnumerable<string> collection)
{
    return collection.SelectMany(c => c.Split(' '));
}

Here, this would evaluate to { "2.4", "kWh", "@", "105.00", "c/kWh", "this", "is", "a", "test" }.

Or if I'm misunderstanding you and you actually do want an array of arrays,

public IEnumerable<string[]> SplitAll(IEnumerable<string> collection)
{
    return collection.Select(c => c.Split(' '));
}

Here, { { "2.4", "kWh", "@", "105.00", "c/kWh" }, { "this", "is", "a", "test" } }.

Or if I'm totally misunderstanding you and you just want to split the one string, that's even easier, and I've already shown it, but you can use string.Split.

Upvotes: 1

Related Questions