简体   繁体   中英

How to count paragraphs in a text?

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
    }

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM