Menus

Tuesday, December 4, 2012

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

No comments:

Post a Comment