7

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

4

6 Answers 6

18

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

string firstLetters = string.Concat(str.TakeWhile(char.IsLetter)); 
Sign up to request clarification or add additional context in comments.

Comments

5

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!

3 Comments

This pattern does not match strings beginning with a lower case alpha
@Joe_DM As far as I'm concerned, post codes don't have lowercases, right?
I'm not in America so I'd agree simply because post codes don't have any letters. Op uses post code as example but please consider other people who find this question later with different requirments. Also, who ever trusted a user to input perfect data. ^([a-zA-Z]+) should match everything.
2

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()); 

6 Comments

why the string builder?
@Mhd.Tahawi Faster than concatenating to a string.
@Mhd.Tahawi the sample posted by the op is small, but who knows how long this could be in production? What if the string has 1000 characters before the first non numeric? string is immutable and so we wouldn't want to create 1000 new reference type objects on the stack.
@Joe_DM, True, maybe I was not clear. why loop and concatenate when you can just do substr
@Mhd.Tahawi Are you saying, loop to find the indexOf the first non alpha, then break the loop and do a substring.... I could get on board with that! :)
|
1

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.

4 Comments

there are many non alpha numeric characters that could appear before a didgit. perhaps postcode.First(!Char.IsLetter) ?
FirstOrDefault won't thow an exception if you're worried about that.
But Substring will in that case (with FirstOrDefault)
Good point, I guess this would need a few external guard clauses to prevent it becoming buggy. Either way, It's a good hint for the op and points him in the right direction :)
0
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 ); 

5 Comments

What about when whitespace appears first, or another non alphanumeric character?
They will be displayed, i.e.: a = "> BL9 8NS", result is = "> BL"
I was thinking about an input value like this "BL ♣ 9 8NS"
a = "BL ♣ 9 8NS", result = "BL ♣"
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
0

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]; } 

1 Comment

int.TryParse(code[i].ToString(), out int _n) - just NO-NO-NO! In .Net you can use char.IsXXX() methods, where XXX - is one of the Unicode categories. char.IsDigit() is one of them. It is much faster and easier to read

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.