Sam
Sam

Reputation: 303

How to get only first letters from string in C#

I am new to C# and I am using windows forms. I am dealing with Postcodes string and I am trying to get the first letters from the Post code and store it in a variable, for example:

BL9 8NS (I want to get BL)

L8 6HN (I want to get L)

CH43 7TA (I want to get CH)

WA8 7LX (I want to get WA)

I just want to get the first letters before the number and as you can see the number of letters can be 1 or 2 and maybe 3. Anyone knows how to do it? Thank you

Upvotes: 7

Views: 7186

Answers (6)

mshwf
mshwf

Reputation: 7449

While the answer of Ofir Winegarten is really great, I up-voted it, I wanted to share my answer I wrote before the sudden power cut!

string code = "BL9 8NS";
string myStr = "";
for (int i = 0; i < code.Length; i++)
  {
     if (char.IsNumber(code[i]))
         break;
     else
         myStr += code[i];
  }

Upvotes: 0

NotADeveloper
NotADeveloper

Reputation: 347

What about

string result = postcode.Substring(0, postcode.IndexOf(postcode.First(Char.IsDigit)));

If your postcodes will always contain that digit, First won't throw any exception.

Upvotes: 1

creg
creg

Reputation: 164

char[] numbers = new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

string a = "BL9 8NS";
string result = a.Substring( 0, a.IndexOfAny(numbers) );
Console.WriteLine( result );

Upvotes: 0

Sweeper
Sweeper

Reputation: 271040

Use a regex with a group to match the first letters.

This is the regex you need:

^([a-zA-Z]+)

You can use it like this:

Regex.Match("BL9 8NS", "^([a-zA-Z]+)").Groups[1].Value

The above expression will evaluate to "BL".

Remember to add a using directive to System.Text.RegularExpressions!

Upvotes: 5

GregorMohorko
GregorMohorko

Reputation: 2857

You can use StringBuilder and loop through the characters until the first non-letter.

string text = "BL9 8NS";
StringBuilder sb = new StringBuilder();
foreach(char c in text) {
    if(!char.IsLetter(c)) {
        break;
    }
    sb.Append(c);
}
string result = sb.ToString(); // BL

Or if you don't care about performance and just want it simple, you can use TakeWhile:

string result = new string(text.TakeWhile(c => char.IsLetter(c)).ToArray());

Upvotes: 2

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

Since string imlements IEnumerable<char>, using Linq TakeWhile and char.IsLetter would be very easy:

string firstLetters = string.Concat(str.TakeWhile(char.IsLetter));

Upvotes: 18

Related Questions