0

I'm stuck. I have song text stored in a string. I need to count the song houses (houses separates by empty line. empty line is my delimiter). In addition I need an access to each word, so i can associate the word to its house. I really will appreciate yours help

This is my base code:

 var paragraphMarker = Environment.NewLine;
    var paragraphs = fileText.Split(new[] {paragraphMarker},
                                    StringSplitOptions.RemoveEmptyEntries);
    foreach (var paragraph in paragraphs)
    {
        var words = paragraph.Split(new[] {' '}, 
                              StringSplitOptions.RemoveEmptyEntries)
                             .Select(w => w.Trim());
        //do something
    }
Coby Abutbul
  • 55
  • 1
  • 8

2 Answers2

1

You should be able to perform Regex.Split on \r\n\r\n which would be two carridge return line feeds (assuming that your empty line is actually empty) and then String.Split those by ' ' to get the individual words in each paragraph.

This will break it apart into two sections and then count the words in each. For simplicity I've only got one sentence in each bit.

var poem = "Roses are red, violets are blue\r\n\r\nSomething something darkside";
var verses = System.Text.RegularExpressions.Regex.Split(poem, "\r\n");
foreach (var verse in verses)
{
  var words = verse.Split(' ');
  Console.WriteLine(words.Count());
}

You'll need to tidy up more edge cases like punctuation etc, but this should give you a starting point.

Community
  • 1
  • 1
NikolaiDante
  • 18,469
  • 14
  • 77
  • 117
-1

String.Split will create an array using your delimiter as a token.
Array.Count will tell you how many elements are in an array.

For example, to find the count of words in this sentence:

var count = @"Hello! This is a naive example.".Split(' ').Count;
Sam Axe
  • 33,313
  • 9
  • 55
  • 89