How to check if a word starts with a given character?

sara picture sara · Mar 20, 2013 · Viewed 63.8k times · Source

I have a list of a Sharepoint items: each item has a title, a description and a type. I successfully retrieved it, I called it result. I want to first check if there is any item in result which starts with A then B then C, etc. I will have to do the same for each alphabet character and then if I find a word starting with this character I will have to display the character in bold.

I initially display the characters using this function:

private string generateHeaderScripts(char currentChar)
{
    string headerScriptHtml = "$(document).ready(function() {" +
        "$(\"#myTable" + currentChar.ToString() + "\") " +
        ".tablesorter({widthFixed: true, widgets: ['zebra']})" +
        ".tablesorterPager({container: $(\"#pager" + currentChar.ToString() +"\")}); " +
        "});";
    return headerScriptHtml;
}

How can I check if a word starts with a given character?

Answer

Dmitriy Khaykin picture Dmitriy Khaykin · Mar 20, 2013

To check one value, use:

    string word = "Aword";
    if (word.StartsWith("A")) 
    {
        // do something
    }

You can make a little extension method to pass a list with A, B, and C

    public static bool StartsWithAny(this string source, IEnumerable<string> strings)
    {
        foreach (var valueToCheck in strings)
        {
            if (source.StartsWith(valueToCheck))
            {
                return true;
            }
        }

        return false;
    }

    if (word.StartsWithAny(new List<string>() { "A", "B", "C" })) 
    {
        // do something
    }

AND as a bonus, if you want to know what your string starts with, from a list, and do something based on that value:

    public static bool StartsWithAny(this string source, IEnumerable<string> strings, out string startsWithValue)
    {
        startsWithValue = null;

        foreach (var valueToCheck in strings)
        {
            if (source.StartsWith(valueToCheck))
            {
                startsWithValue = valueToCheck;
                return true;
            }
        }

        return false;
    }

Usage:

    string word = "AWord";
    string startsWithValue;
    if (word.StartsWithAny(new List<string>() { "a", "b", "c" }, out startsWithValue))
    {
        switch (startsWithValue)
        {
            case "A":
                // Do Something
                break;

            // etc.
        }
    }