Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string manipulation in c#

Tags:

string

c#

.net

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.

like image 842
Saeid Yazdani Avatar asked Apr 08 '11 11:04

Saeid Yazdani


2 Answers

do you mean:

var list = mainString.Split('\\');
return list[list.Length-1];
like image 96
Aliostad Avatar answered Nov 07 '22 01:11

Aliostad


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.

like image 40
Mikael Östberg Avatar answered Nov 07 '22 01:11

Mikael Östberg