How to check if a word starts with a given character?
Asked Answered
F

9

22

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?

Fleeting answered 20/3, 2013 at 14:55 Comment(1)
I might not understand your question, but if you can parse it to a string you can use the .StartsWithUndecagon
C
48

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.
        }
    }
Cotemporary answered 20/3, 2013 at 15:1 Comment(4)
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])Hospital
I prefer the readability of "StartsWithAny", but it also depends on the amount of reuse expected.Cotemporary
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!Myocardiograph
@Hospital It's not overkill. Like OP has stated, StartsWithAny is more readable, and can be re-used in many places.Myocardiograph
M
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.

Marhtamari answered 20/3, 2013 at 15:26 Comment(0)
A
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

Alisaalisan answered 20/3, 2013 at 15:0 Comment(0)
D
1

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

    if (Word.Substring(0,1) == "A") {
    }
Danforth answered 20/3, 2013 at 15:6 Comment(0)
R
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.

Recovery answered 19/8, 2020 at 12:30 Comment(0)
A
0

To return the first character in a string, use:

Word.Substring(0,1) //where word is a string
Arri answered 20/3, 2013 at 14:59 Comment(0)
T
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.

Twentyfour answered 20/3, 2013 at 15:6 Comment(0)
S
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);
}
Shellans answered 24/8, 2023 at 5:0 Comment(2)
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.Extradition
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.Shellans
S
0

UPDATE: you could use method overload

public bool StartsWith (char value)

Available from versions .NET Core 2.0 and .NET Standard 2.1

Speaker answered 22/3 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.