21

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?

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
sara
  • 215
  • 1
  • 2
  • 8

8 Answers8

47

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.
        }
    }
Dmitriy Khaykin
  • 5,238
  • 1
  • 20
  • 32
  • 1
    Is it not overkill to write an extension method for something that can already be easily written as `new []{'a', 'b', 'c'}.Contains(s[0])` – Magnus Mar 20 '13 at 15:20
  • 1
    I prefer the readability of "StartsWithAny", but it also depends on the amount of reuse expected. – Dmitriy Khaykin Mar 20 '13 at 15:22
  • Thanks! This -- the extension method with the `out` parameter, is exactly what I was thinking of writing for my needs, which is to check incoming route segment against a list of route url segments. Works like a charm! – Shiva May 22 '17 at 00:33
  • @Magnus It's not overkill. Like OP has stated, `StartsWithAny` is more readable, and can be re-used in many places. – Shiva May 22 '17 at 00:33
2

You could do something like this to check for a specific character.

public bool StartsWith(string value, string currentChar) {
   return value.StartsWith(currentChar, true, null);
}

The StartsWith method has an option to ignore the case. The third parameter is to set the culture. If null, it just uses the current culture. With this method, you can loop through your words, run the check and process the word to highlight that first character as needed.

uadrive
  • 1,249
  • 14
  • 23
1

Assuming the properties you're checking are string types, you can use the String.StartsWith() method.. for example: -

if(item.Title.StartsWith("A"))
{
    //do whatever
}

Rinse and repeat

DGibbs
  • 14,316
  • 7
  • 44
  • 83
1

Try the following below. You can do either StartsWith or Substring 0,1 (first letter)

    if (Word.Substring(0,1) == "A") {
    }
apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69
1

You can simply check the first character:

string word = "AWord"
if (word[0] == 'A')
{
    // do something
}

Remember that character comparison is more efficient than string comparison.

Shadi Serhan
  • 309
  • 3
  • 9
0

To return the first character in a string, use:

Word.Substring(0,1) //where word is a string
Daniel Möller
  • 84,878
  • 18
  • 192
  • 214
0

You could implement Regular Expressions. They are quite powerful, but when you design your expression it will actually accomplish a task for you.

For example finding a number, letter, word, and etc. it is quite expressive and flexible.

They have a really great tutorial on them here:

An example of such an expression would be:

string input = "Some additional string to compare against.";
Match match = Regex.Match(input, @"\ba\w*\b", RegexOptions.IgnoreCase);

That would find all the items that start with an "a" no matter the case. You find even utilize Lambda and Linq to make them flow even better.

Hopefully that helps.

Greg
  • 11,302
  • 2
  • 48
  • 79
0

To extend on the accepted answer, you can make the StartsWithAny extension method into a oneliner:

public static bool StartsWithAny(this string source, IEnumerable<string> values)
{
    return values.Any(source.StartsWith);
}
LW001
  • 2,452
  • 6
  • 27
  • 36
Samuel8000
  • 51
  • 1
  • 7
  • This is the best answer in my opinion. I would just suggest you to check for null values before it to prevent null reference exceptions. – Junior Grão Aug 25 '23 at 19:48
  • I totally agree with the NRE remark, but I would check it before calling this extension method as its responsibility is to check if source.StartsWith. But again, checking for nulls is certainly always needed. – Samuel8000 Aug 26 '23 at 20:36