I have a string like this, that is some names separated by some backslashes:
string mainString = @"Sean\John\Rob\fred";
How can I get the last name in above string format, in this case "fred", while I want the name to be the last name in the string (after all backslashes)?
Thanks.
do you mean:
var list = mainString.Split('\\');
return list[list.Length-1];
You could use LINQ to solve this:
string mainString = @"Sean\John\\Rob\fred";
var fred = mainString
.Split("\\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Last();
You could also use LastOrDefault()
to protect yourself against an empty string or a string that doesn't contain any \
. Then fred
would just be null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With