I am looking for how to get rid off below exception "Index was outside the bounds of the array." for the below case 2
Aim: To separate the first name and last name (last name may be null some times)
Case 1:
Name: John Melwick
I can be able to resolve the first case with my code
Case 2:
Name: Kennedy
In case two I am getting an error Index was out of range at LastName in my code
Case 3:
Name: Rudolph Nick Bother
In case 3, I can be able to get:
FirstName: Rudolph and LastName: Nick (whereas I need Nick Bother together to be lastname)
Very much thankful, if anybody help me.
Here is the code:
Match Names = Regex.Match(item[2], @"(((?<=Name:(\s)))(.{0,60})|((?<=Name:))(.{0,60}))", RegexOptions.IgnoreCase);
if (Names.Success)
{
FirstName = Names.ToString().Trim().Split(' ')[0];
LastName = Names.ToString().Trim().Split(' ')[1];
}
Split the string with a limit on the number of substrings to return. This will keep anything after the first space together as the last name:
string[] names = Names.ToString().Trim().Split(new char[]{' '}, 2);
Then check the length of the array to handle the case of only the lastname:
if (names.Length == 1) {
FirstName = "";
LastName = names[0];
} else {
FirstName = names[0];
LastName = names[1];
}
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