简体   繁体   中英

How do you grab the first letter in a string?

I'm working with an entity (Employee) that has 3 fields: FirstName, LastName, & Login

I want to grab the lastname and the first letter of the firstname field and write this to the login field. 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:

char firstCharOfFirstName = someEmployee.FirstName.Trim()[0];

(As the other answers mention it's good to check for empty string and null string)

Bear in mind, SubString() or FirstName[0] will throw a ArgumentOutOfRangeException or IndexOutOfRangeException if

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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