Count Words and Characters In a String

Simple way you can use Regular Expression

    string strOriginal = "These functions will come handy";
    string strModified = String.Empty;

// Count words
    System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
    MessageBox.Show(wordColl.Count.ToString());

    // Count characters. White space is treated as a character
    System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
    MessageBox.Show(charColl.Count.ToString());


0 comments: