[英]How do you grab the first letter in a string?
I'm working with an entity (Employee) that has 3 fields: FirstName, LastName, & Login 我正在使用一个有3个字段的实体(Employee):FirstName,LastName和Login
I want to grab the lastname and the first letter of the firstname field and write this to the login field. 我想获取姓氏和firstname字段的第一个字母,并将其写入登录字段。 How do I grab the first letter of the firstname?
我如何获取名字的第一个字母?
Thanks for any help. 谢谢你的帮助。
Just as simple as: 就像这样简单:
if (!string.IsNullOrEmpty(Employee.FirstName))
{
string firstLetter = Employee.FirstName.SubString(0, 1);
}
With that you get the first letter as a string and with this the character: 有了这个,你得到第一个字母作为字符串,并用这个字符:
if (!string.IsNullOrEmpty(Employee.FirstName))
{
char firstLetter = Employee.FirstName[0];
}
To get the first character (not necessarily a letter) use an index into the string: 要获取第一个字符 (不一定是字母),请在字符串中使用索引:
char c = employee.FirstName[0];
You may also want to first check that the string is non-null and non-empty and strip leading whitespace, and that the first character is actually a letter: 您可能还想首先检查字符串是否为非空且非空并剥离前导空格,并且第一个字符实际上是一个字母:
if (employee != null && employee.FirstName != null) {
string name = employee.FirstName.TrimStart();
if (name.Length > 0) {
char firstChar = name[0];
if (char.IsLetter(firstChar)) {
employee.Login = firstChar.ToString();
}
}
}
char firstCharOfFirstName = someEmployee.FirstName[0];
If the FirstName field can have leading whitespace you can do: 如果FirstName字段可以有前导空格,您可以执行以下操作:
char firstCharOfFirstName = someEmployee.FirstName.Trim()[0];
(As the other answers mention it's good to check for empty string and null
string) (正如其他答案所提到的,检查空字符串和
null
字符串是件好事)
Bear in mind, SubString() or FirstName[0] will throw a ArgumentOutOfRangeException
or IndexOutOfRangeException
if 请记住,如果SubString()或FirstName [0]将抛出
ArgumentOutOfRangeException
或IndexOutOfRangeException
,
FirstName == string.Empty
So, this code will at least avoid exception: 所以,这段代码至少会避免异常:
if(str2 != null)
{
char result = (str2.Length > 0)
? str2[0]
: (char)0;
}
Don't forget this code will return a false result if the string is empty! 如果字符串为空,请不要忘记此代码将返回错误结果!
If the first name might be empty, you would have to check that when getting the first letter: 如果名字可能为空,则在获取第一个字母时必须检查:
FirstName.Substring(0, Math.Min(FirstName.Length, 1))
This will give you an empty string if the FirstName
string is empty, otherwise the first character as a string, so that you can concatenate it with the last name. 如果
FirstName
字符串为空,这将为您提供一个空字符串,否则将第一个字符作为字符串,以便您可以将其与姓氏连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.