-1

I have a string that I want to get a specific part of.

the string will always be in the format of:

FirstName LastName, (Position)

I want to be able to get just the LastName part of the string (after the first space and before the comma)

the LastName part of the string will always be different but the FirstName may be the same

how would i go about doing this

John Saunders
  • 159,224
  • 26
  • 237
  • 393
NattyMan0007
  • 93
  • 13
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Dec 16 '13 at 01:56
  • ok no worries, the question has already been answered though – NattyMan0007 Dec 16 '13 at 02:06

4 Answers4

2

If the string is always in the format FirstName LastName, (Postion), you can use String.Split to split the string into 3 elements based on space, and the String.Replace method to remove the comma from the LastName:

string input = "John Doe, (Manager)";

string lastName = input.Split(' ')[1].Replace(",", "");

The above splits the string on ' ', returning an array of strings (element 0 is John, element 1 is Doe, and element 2 is (Manager)). Next the second element is selected ([1]), and then String.Replace is used to remove the comma.

The output should be "Doe".

Tim
  • 27,799
  • 8
  • 61
  • 74
2

Simpler approach:

 var test = "FirstName LastName, (Position)";
 var t = test.Split(new[] { ' ', ',' })[1];
Adarsh Shah
  • 6,639
  • 2
  • 22
  • 38
0

You can use Substring for this

int spaceIndex = str.IndexOf(' ');
string lastName = str.Substring(spaceIndex);

but this only works if all firstnames have same length.for better way you can consider using Split method:

string lastName = str.Split(' ')[1];
Selman Genç
  • 97,365
  • 13
  • 115
  • 182
  • The first approach will not satisfy OP's requirement, as it will result in " LastName, (Position)". The second approach is closer, but will still have the `,` at the end. – Tim Dec 16 '13 at 01:52
0

Well basically you can't do that safely. You can use the String.Split method to separate the Full Name and position into a string array using the comma (,) as a separator, but when it comes to splitting the First Name and Last Name it looks like you can only do that by using space as a separator, which at the same time raises a few questions. What'd happen if there's a middle name?

Examples

string[] fullNameAndPosition = str.Split(',');
string position = fullNameAndPosition[1];
string[] fullName = fullNameAndPosition.Split(' ');
string fname = fullName[0];
string lname = fullName[1];
Leo
  • 14,284
  • 2
  • 36
  • 54