Q:

C# string trimming

I am having trouble on how i should trim this string. I want everything after the last '/' to be deleted, but there are multiple '/'. 
Example: 
From:http://stackoverflow.com/questions/ask/randomcrap.html
To: http://stackoverflow.com/questions/ask/

A:

String trimming can be done using many of the built in string utlitites.
First you want the LastIndexOf the "/" character in the string, and then you want use the Substring method from the index of 0 (start of the string) to the index of the / character. Now this will return everything to the last / if you want to include the slash you have to add one more index.
        static string getToLastSlash(string inString)
        {
            var index = inString.LastIndexOf('/');
            if (index == -1)
                throw new Exception("/ not found in string");

            return inString.Substring(0, index + 1);
        }

The LastIndexOf() method will return the last index of a specific character or string provided. If the LastIndexOf() method does not evaluate a match the result will be -1. Given the fact that you could have a non-match, you must first check if the match result is -1. In the above method we simply throw an exception however your application may have an alternative method to handle this situation.
If the match is greater that -1 then you can assume a match was found. When a match was found you can use the Substring() method to parse all the characters in the string starting at position 0 to the index+1.

A:

I would use a regular expression Replace with an end ($) anchor.
var res = Regex.Replace(input,
    @"[^/]+$", // match all the non-slashes anchored to the end of input
    "");       // replace any matched characters with nothing

// and make sure to use "res"

I prefer to use a regular expression for tasks like this - because I find it simpler and it can avoid an extra conditional guard "for free" - but make sure to understand the mechanics of the approach used.

