Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate a first name and last name in c#?

Tags:

c#

asp.net

c#-4.0

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];
}
like image 350
Cherry Avatar asked Dec 16 '22 05:12

Cherry


1 Answers

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];
}
like image 91
Guffa Avatar answered Jan 26 '23 00:01

Guffa