1

I have a scenario where I am getting a comma separated string LastName, FirstName. I have to convert it into FirstName LastName.

My code is below:

Public static void main(string [] args)
{
      var str = "Lastname, FirstName":
      var strArr = str.Split(',');
      Array. Reverse(strArr);
      var output = string.join(" ", strArr);
}

Is there a better way to do this, like in one line or using LINQ?

4
  • Like output = strArr[1] + " " + strArr[0]; ? By the way you are not removing the white space in front of FirstName value, add a Trim() to your string instances to do that. Commented Apr 14, 2017 at 11:38
  • don't forget to remove whitespaces after splitting your string Commented Apr 14, 2017 at 11:39
  • @igor I had done that intially but it failed as sometimes I am getting string.empty or only first name.. Commented Apr 14, 2017 at 11:39
  • Maybe this question should be migrated to Code Review ? Commented Apr 14, 2017 at 12:03

4 Answers 4

1

Yes there is already a Reverse extension method for IEnumerables:

var output = string.Join(" ",str.Split(',').Reverse());
Sign up to request clarification or add additional context in comments.

Comments

1

This takes care of a lot of the various edge cases. You mentioned one but did not include it in your initial question so I assume there could be others.

var tests = new[]{"Lastname, FirstName", "Lastname, ", ", FirstName", "Lastname", "FirstName"};
foreach(var str in tests)
{
    var strArr = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
        .Where(x => !string.IsNullOrWhiteSpace(x))
        .Reverse()
        .Select(x => x.Trim());
    var output = string.Join(" ", strArr);
    Console.WriteLine(output);
}

Working Fiddle

Comments

1

Use Aggregate and Trim your names after splitting, you do not need reversing.

 str.Split(',').Aggregate((lname, fname) => fname.Trim() + " " + lname.Trim())

Comments

0

Below is my new code:

Public static void main(string [] args)
    {
          var str = "Lastname, FirstName":
          var strArr = str.Split(',').Select(p=>p.Trim()).ToArray();
          var output = string.join(" ", strArr.Reverse());
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.