Find Uppercase words in a String using C#

I am helping a friend to build an Editor API in C#. One of the functionalities in the Editor is to filter uppercase words in a string and highlight them. Here’s a sample of how uppercase words can be filtered in a string

static void Main(string[] args)
{
// code from DevCurry.com
var strwords = FilterWords("THIS is A very STRANGE string");
foreach (string str in strwords)
Console.WriteLine(str);
Console.ReadLine();
}

static IEnumerable<string> FilterWords(string str)
{
var upper = str.Split(' ')
.Where(s => String.Equals(s, s.ToUpper(),
StringComparison.Ordinal));

return upper;

}

The code shown above is quite simple. The FilterWords method accepts a string, uses the Split() function to split the string into a string array based on a space delimiter and finally compares each string to its upper case. All the matches are then returned to the caller function.

OUTPUT

Uppercase string filter

1 comment:

  1. good article.

    another similar piece of code with simplicity,
    string l5 = "INDIA is a small COUNTRY";
    var output5 = l5.Split(' ').Where(x => x == x.ToUpper());
    string output6 = output5.Aggregate((item1, item2) => item1 + " " + item2);

    //OUTPUT: INDIA COUNTRY - FETCH ONLY UPPERCASE WORDS

    ReplyDelete