0

I Have a string
string name="ajsbbc<<(either hold an alphabet or some symbol at the end )
Now i want a condition that identify a string contain [a-zA-Z] at the end(true/false)

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
RollerCosta
  • 5,020
  • 9
  • 53
  • 71

4 Answers4

4

Here is a Regex solution:

Regex.IsMatch(name, "[a-zA-Z]$");
Phil Klein
  • 7,344
  • 3
  • 30
  • 33
3

There is a function in the Char class that does this already.

    string name = "ajsbbc";

    if (Char.IsLetter(name[name.Length - 1]))
        Console.WriteLine("True");
    else
        Console.WriteLine("False");
colton7909
  • 824
  • 12
  • 16
  • This matches more than A-Za-z this will write true for Café `"Caf\u00e9" // U+00E9 LATIN SMALL LETTER E WITH ACUTE` but then again will write false for when a grapheme is used in Café `"Cafe\u0301" // U+0301 COMBINING ACUTE ACCENT` see http://stackoverflow.com/questions/2056866/enumerating-a-string-by-grapheme-instead-of-character for a solution that can deal with a grapheme – Conrad Frix Dec 15 '11 at 05:55
1

store last char of your string at temp string and then check your temp string with regular exp
Regex lettersOnly = new Regex("^[a-zA-Z]$");
where

  • ^ means "begin matching at start of string"
  • [a-zA-Z] means "match lower case and upper case letters a-z"
  • $ means "only match if cursor is at end of string"
    tri it (i am not sure if it work)
RollerCosta
  • 5,020
  • 9
  • 53
  • 71
0

You can use this function and send your string as parameter to this

    private bool IsAlphabet(string input)
    {
        bool alphabet = false;

        char ch = input[input.Length - 1];

        if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
            alphabet = true;

        return alphabet;
    }
Ajit Vaze
  • 2,686
  • 2
  • 20
  • 24
  • Ajit will you please explain me the condition you mentioned above , just for my sake and not to test your knowlwdge(i mean is it possible to apply aloop in if condition over alphabets) – RollerCosta Dec 15 '11 at 04:57
  • Some suggestion. You need to check whether the string is null or empty. Also you just say return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')); and avoid the local bool variable. you can also make this an extension method. – ferosekhanj Dec 15 '11 at 05:00