Search This Blog

Friday, April 5, 2013

C# Code To Extract Only Alphabets From A String

Sometimes we may need to remove all numbers and special characters from a string.
This can be done using ASCII vaues of characters.

Following code snippet will extract only alphabets  from a string using ASCII codes.

public static string GetAlphabets(string strText)
{
    string strAlphabets="";
    for(int i=0;i<strText.Length;i++)
    {
        char chr=strText[i];
        if(chr>=65 && chr<=90)
        {
            strAlphabets=strAlphabets+chr;
        }
        else if (chr >= 97 && chr <= 122)
        {
            strAlphabets = strAlphabets + chr;
        }
       
    }
    return strAlphabets;
}
 
             
Usage:
           string strTxt = "ABCD1234!@#$abcdefgh";
            Console.WriteLine("The string is " + strTxt);
            Console.WriteLine("Output: "+  GetAlphabets(strTxt));
 


Output:

No comments:

Post a Comment