1

I have a problem with my array. My array name is word[3] have 3 items.

word[0] = "Listen Repeat"
word[1] = "Tune"
word[2] = "Landing Page"

I want words[0] split new two item and add to exist item in array.

words = Regex.Split(words[0], @"\s{1,}").Where(x => !string.IsNullOrEmpty(x)).ToArray(); 

So, my array becomes like:

word[0] = "Listen"
word[1] = "Repeat"

But I want my array like:

word[0] = "Listen"
word[1] = "Repeat"
word[2] = "Tune"
word[3] = "Landing Page"

Note: If using add two arrays, this arrays not sort. You can see my next item in array like:

word[0] = "Listen"

to word[1] = "Repeat"

to word[2] = "Tune"

to word[3] = "Langding Page"

If I using AddRange this will like:

from word[0] = "Listen"

to word[1] = "Tune"

to word[2] = "Langding Page"

to word[3] = "Repeat"

This code will delete exist item and create new arrays with two items. I don't know how to add exist array.

I tried with Append but it not success.

Ave
  • 4,338
  • 4
  • 40
  • 67
  • Very unclear what you've tried - array does not have `Append`... There are many questions discussion adding/replacing items in array / merging arrays in all possible ways. Make sure to provide results of your research as links with sample code that did not work (see [MCVE] for guidance on code samples). – Alexei Levenkov Jun 18 '16 at 03:45
  • @AlexeiLevenkov. Almost in Stackoverflow. You add two arrays. At here: http://stackoverflow.com/questions/1547252/how-do-i-concatenate-two-arrays-in-c But your array not sorted. You can see my next item in array like `word[0] = "Listen"` to `word[1] = "Repeat"`. If I using `AddRange` this will like: `word[0] = "Listen"` to `word[1] = "Tune"` to `word[2] = "Langding Page"` to `word[3] = "Repeat"` – Ave Jun 18 '16 at 03:51

1 Answers1

2

You can do it via linq and use SelectMany

var word = new string[3];
word[0] = "Listen Repeat";
word[1] = "Tune";
word[2] = "Landing Page";

word = word.SelectMany(x => Regex.Split(x, @"\s{1,}").Where(x => !string.IsNullOrEmpty(x))).ToArray();

If you just want to split a specific item then you can use this function.

public static string[] SplitItem(string[] input, int index)
{
    var l = new List<string>(input.Length);
    l.AddRange(input.Take(index));
    l.AddRange(Regex.Split(input[index], @"\s{1,}").Where(y => !string.IsNullOrEmpty(y)));
    l.AddRange(input.Skip(index + 1).TakeWhile(x => true));
    return l.ToArray();
}


var word = new string[3];
word[0] = "Listen Repeat";
word[1] = "Tune";
word[2] = "Landing Page";

word = SplitItem(word,0);
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74