Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand way to remove last forward slash and trailing characters from string

Tags:

string

c#

If I have the following string:

/lorem/ipsum/dolor

and I want this to become:

/lorem/ipsum

What is the short-hand way of removing the last forward slash, and all characters following it?

I know how I can do this by spliting the string into a List<> and removing the last item, and then joining, but is there a shorter way of writing this?

My question is not URL specific.

like image 949
Curtis Avatar asked Oct 17 '12 14:10

Curtis


2 Answers

You can use Substring() and LastIndexOf():

str = str.Substring(0, str.LastIndexOf('/'));

EDIT (suggested comment)
To prevent any issues when the string may not contain a /, you could use something like:

int lastSlash = str.LastIndexOf('/');
str = (lastSlash > -1) ? str.Substring(0, lastSlash) : str;

Storing the position in a temp-variable would prevent the need to call .LastIndexOf('/') twice, but it could be dropped in favor of a one-line solution instead.

like image 71
newfurniturey Avatar answered Nov 24 '22 05:11

newfurniturey


If there is '/' at the end of the url, remove it. If not; just return the original one.

var url = this.Request.RequestUri.ToString();
url = url.EndsWith("/") ? url.Substring(0, url.Length - 1) : url;
url += @"/mycontroller";
like image 40
Xin Avatar answered Nov 24 '22 07:11

Xin