How to get only the first letters of a string in C #

I am new to C # and I am using windows forms. I am dealing with a Postcodes string, and I am trying to get the first letters of the zip 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. Does anyone know how to do this? thank you

+5
source share
6 answers

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

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

Use the regular expression with the group according to the first letters.

This is the regular expression you need:

 ^([a-zA-Z]+) 

You can use it as follows:

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

The above expression will be evaluated as "BL".

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

+5
source

You can use StringBuilder and scroll characters to the first nebukt.

 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 to be simple, you can use TakeWhile :

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

What about

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

If your zip codes always contain this number, First will not raise any exceptions.

+1
source
 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 ); 
0
source

Although Ofir Winegarten's answer is really wonderful, I voted for it, I wanted to share my answer, which I wrote before the sudden blackout!

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

Source: https://habr.com/ru/post/1269850/


All Articles