简体   繁体   English

如何在C#中只从字符串中获取第一个字母

[英]How to get only first letters from string in C#

I am new to C# and I am using windows forms. 我是C#的新手,我正在使用Windows窗体。 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: 我正在处理Postcodes字符串,我试图从Post代码中获取第一个字母并将其存储在变量中,例如:

BL9 8NS (I want to get BL) BL9 8NS(我想获得BL)

L8 6HN (I want to get L) L8 6HN(我想得到L)

CH43 7TA (I want to get CH) CH43 7TA(我想得到CH)

WA8 7LX (I want to get WA) WA8 7LX(我想要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? 我只想获得数字前面的第一个字母,你可以看到字母的数量可以是1或2,也许3.任何人都知道怎么做? Thank you 谢谢

由于string imlements IEnumerable<char> ,使用Linq TakeWhilechar.IsLetter非常容易:

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". 上述表达式将评估为“BL”。

Remember to add a using directive to System.Text.RegularExpressions ! 请记住向System.Text.RegularExpressions添加using指令!

You can use StringBuilder and loop through the characters until the first non-letter. 您可以使用StringBuilder并遍历字符,直到第一个非字母。

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 : 或者,如果您不关心性能并且只是想简单,您可以使用TakeWhile

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

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. 如果您的邮政编码始终包含该数字,则First不会抛出任何异常。

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

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! 虽然Ofir Winegarten的答案真的很棒,但我还是投了票,我想分享我在突然断电前写的答案!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM