'String.join array from last element
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?
Solution 1:[1]
Yes there is already a Reverse extension method for IEnumerables:
var output = string.Join(" ",str.Split(',').Reverse());
Solution 2:[2]
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);
}
Solution 3:[3]
Use Aggregate and Trim your names after splitting, you do not need reversing.
str.Split(',').Aggregate((lname, fname) => fname.Trim() + " " + lname.Trim())
Solution 4:[4]
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());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cetin Basoz |
Solution 2 | Igor |
Solution 3 | |
Solution 4 | vinzee |