Anyname Donotcare
Anyname Donotcare

Reputation: 11423

How to get the first and the last parts of string separated by a space

If I have a name consists of more than one part separated by a space, and I want to get:

the first name + " " + the last name.

Is there any way to do that.

Example:

john depp lennon

To:

john lennon

Upvotes: 2

Views: 2325

Answers (3)

Meligy
Meligy

Reputation: 36624

Since you mentioned LINQ in the tags, I'll get you that, skipping validation for entering one part (only "Johm") or entering nothing at all, that will be:

Ensure you have:

using System.Linq;

Then:

var nameParts = name.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var fullName = string.Format("{0} {1}", nameParts.First(), nameParts.Last());

Thise will do the job for the happy path


If we want to check for edge cases, we can add extra checks:

static string GetName(string nameEntry)
{
    // assuming .NET 4, or use string.IsNullOrEmpty(), 
    //    as we are protected later from white space-only text
    if(string.IsNullOrWhiteSpace(nameEntry))
        return string.Empty; // Or throw error. Your choice

    var nameParts = nameEntry.Split(new[] { ' ' }, 
                                        StringSplitOptions.RemoveEmptyEntries);
    if(!nameParts.Any()) return string.Empty(); // Or throw error. Your choice

    if(nameParts.Length == 1)
        return nameParts.First();

    var fullName = string.Format("{0} {1}", nameParts.First(), nameParts.Last());
    return fullName;
}

Upvotes: 3

Surjit Samra
Surjit Samra

Reputation: 4662

string str = "john depp lennon";      
string[] data = str.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string result = string.Format("{0} {1}", data.First(), data.Last());

Upvotes: 2

Shai
Shai

Reputation: 25595

string sString = "john depp lennon";
string[] sArray = sString.Split(' ');

string sStartEnd = sArray[0] + " " + sArray[sArray.Count()-1]; // "john lennon"

Upvotes: 5

Related Questions