4

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];
}
gotnull
  • 26,454
  • 22
  • 137
  • 203
Cherry
  • 675
  • 3
  • 10
  • 28
  • 1
    This has been answered here already: http://stackoverflow.com/questions/6629136/how-to-separate-full-name-string-into-firstname-and-lastname-string – gotnull Oct 14 '13 at 23:52
  • Voting to close as a duplicate of the above. – John Saunders Oct 14 '13 at 23:57
  • How do you know that the first string is the first name and the other strings are the last name? For example, there's a fellow named Billy Ray Cyrus... First Name: Billy Ray, Last Name: Cyrus. – Matthew Oct 15 '13 at 00:02
  • See also http://stackoverflow.com/questions/1122328/first-name-middle-name-last-name-why-not-full-name/ – John Saunders Oct 15 '13 at 00:12
  • @Matthew I am not sure about first name, last name ..but it was the request asked by the person and they are going to considered as after the first name remaining part will be lastname only. I am checking it if there is any optional code here... – Cherry Oct 15 '13 at 00:14

6 Answers6

11

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];
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Use

String.indexof(" ")

And

string.lastindexof(" ")

if they match there is one space. If they dont there is 2. I believe it returns 0 if there are no matches. Hope this helps

edit

if you use the indexes you can do a substring using them and get the last name as you are wanting

Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
1

Something like this works:

string name = "Mary Kay Jones" ;
Regex rxName = new Regex( @"^\s*(?<givenName>[^\s]*)(\s+(?<surname>.*))?\s*$") ;
Match m = rxName.Match( name ) ;

string givenName = m.Success ? m.Groups[ "givenName" ].Value : "" ;
string surname   = m.Success ? m.Groups[ "surname"   ].Value : "" ;

But it is an extremely erroneous assumption that a given name consists only of a single word. I can think of many examples to the contrary, such as (but by no means limited to):

  • Billy Ray (as in the earlier example of "Billy Ray Cyrus")
  • Mary Kay
  • Mary Beth

And there's no real way to know without asking the person in question. Does "Mary Beth Jones" consist a given, middle and surname or does consist of a given name, Mary Beth and a surnname "Jones".

If you are considering English-speaking cultures, the usual convention is that one may have as many given names (forenames) followed by a family name (surname). Prince Charles, heir to the British Crown, for instance carries the rather heavy-duty Charles Phillip Arthur George Mountbatten-Windsor. Strictly speaking, he has no surname. Mountbatten-Windsor is used when one is required and his full name is just "Charles Phillip Arthur George".

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0
string fullName = "John Doe";
var names = fullName.Split(' ');
string firstName = names[0];
string lastName = names[1];

The reason you're getting an error is because you're not checking for the length of names.

names.Length == 0 //will not happen, even for empty string
names.Length == 1 //only first name provided (or blank)
names.Length == 2 //first and last names provided
names.Length > 2 //first item is the first name. last item is the last name. Everything else are middle names

See this answer for more information.

Community
  • 1
  • 1
gotnull
  • 26,454
  • 22
  • 137
  • 203
0

Modify the code to be something like:

Match Names = Regex.Match(item[2], @"(((?<=Name:(\s)))(.{0,60})|((?<=Name:))(.{0,60}))", RegexOptions.IgnoreCase);

if (Names.Success)
{
  String[] nameParts =  Names.ToString().Trim().Split(' ');
  int count = 0;
  foreach (String part in nameParts) {
    if(count == 0) {
      FirstName = part;
      count++;
    } else {
      LastName += part + " ";
    }
  }
} 
gotnull
  • 26,454
  • 22
  • 137
  • 203
Rami
  • 7,162
  • 1
  • 22
  • 19
0

Here is the most generalized solution for this issue.

public class NameWrapper
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public NameWrapper()
    {
        this.FirstName = "";
        this.LastName = "";
    }
}
 public static NameWrapper SplitName(string inputStr, char splitChar)
   {
       NameWrapper w = new NameWrapper();
       string[] strArray = inputStr.Trim().Split(splitChar);
       if (string.IsNullOrEmpty(inputStr)){
           return w;
       }


       for (int i = 0; i < strArray.Length; i++)
       {
           if (i == 0)
           {
               w.FirstName = strArray[i];
           }
           else
           {
               w.LastName += strArray[i] + " ";
           }
       }
       w.LastName = w.LastName.Trim();

       return w;

   }
Muhammad Adnan
  • 231
  • 3
  • 4