Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only first letters from string in C#

Tags:

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

like image 812
Sam Avatar asked Jul 15 '17 08:07

Sam


People also ask

How do you extract the first letter of a string?

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.

Does C have Substr?

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.

What is the use of '\ 0 in C programming?

'\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.

What is the '\ o character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string.


3 Answers

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

string firstLetters = string.Concat(str.TakeWhile(char.IsLetter));
like image 161
Ofir Winegarten Avatar answered Oct 03 '22 03:10

Ofir Winegarten


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!

like image 36
Sweeper Avatar answered Oct 03 '22 02:10

Sweeper


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());
like image 22
GregorMohorko Avatar answered Oct 03 '22 03:10

GregorMohorko