0

I have a string that I have obtained from a text file. This string contains about 1200 words. The words are separated by spaces - sometimes one space, and sometimes more than one space.

How do I make an array that contains every sixth word (or nth word, for that matter).

samy
  • 14,832
  • 2
  • 54
  • 82

3 Answers3

13

Do a split and then filter by index of the word:

text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)
    .Where((word, index) => index % 6 == 0)
    .ToArray()
Artiom
  • 7,694
  • 3
  • 38
  • 45
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • 1
    yeah, this one looks nicer. Didn't know where has index option – Artiom Aug 14 '15 at 14:29
  • Yeah, the `Where` has the index. Your solution is better Andrei, since you also include the split which I overlooked in my answer – samy Aug 14 '15 at 14:32
3
private string[] GetWords(string path, int step){
    var words = File.ReadAllText(path).Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
    var resultList = new List<string>(words.Length/step);
    for(var i=0; i<words.Length; i+=step)
    {
       var word = words[i];
       resultList.Add(word);
    }
    return resultList.ToArray();
}
Artiom
  • 7,694
  • 3
  • 38
  • 45
0

Simply take all words where index is mod N in your list with a Where linq query:

var words = new List<string> {"word1", "word2", "word3", "word4", "word5", "word6"};
var n = 2;
var nthWords = words.Where((word, index) => (index % n) == 0).ToArray();

nthWords now contains word1 word3 word5

samy
  • 14,832
  • 2
  • 54
  • 82