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
Get the First Letter of the String You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str.
So it turns out that, in C, it's actually impossible to write a proper "utility" substring function, that doesn't do any dynamic memory allocation, and that doesn't modify the original string. All of this is a consequence of the fact that C does not have a first-class string type.
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing In C language it is generally used to mark an end of a string.
\0 is zero character. In C it is mostly used to indicate the termination of a character string.
Since string
imlements IEnumerable<char>
, using Linq TakeWhile
and char.IsLetter
would be very easy:
string firstLetters = string.Concat(str.TakeWhile(char.IsLetter));
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
!
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With