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?
是的,IEnumerables已经有一个反向扩展方法:
var output = string.Join(" ",str.Split(',').Reverse());
分割后使用Aggregate和Trim你的名字,你不需要反转。
str.Split(',').Aggregate((lname, fname) => fname.Trim() + " " + lname.Trim())
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);
}
Sorry for asking such a stupid question, 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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.