12

given any string, i want to remove any letters after a specific character.

this character may exist multiple times in the string and i only want to apply this to the last occurrance.

so lets say "/" is the character, here are some examples:

http://www.ibm.com/test ==> http://www.ibm.com
hello/test ==> hello

leora
  • 188,729
  • 360
  • 878
  • 1,366

3 Answers3

35
if (text.Contains('/'))
    text = text.Substring(0, text.LastIndexOf('/'));

or

var pos = text.LastIndexOf('/');
if (pos >= 0)
    text = text.Substring(0, pos);

(edited to cover the case when '/' does not exist in the string, as mentioned in comments)

Xavier Poinas
  • 19,377
  • 14
  • 63
  • 95
  • 5
    ... assuming that '/' exists in the string. Otherwise you get an `ArgumentOutOfRangeException`. – Phil Hunt Dec 26 '10 at 18:33
  • 1
    For performance, you could run LastIndexOf, and check if result is -1 to check if string contains the character. This way you only search through the string ones, instead of twice (Contains+LastIndexOf) which can be costly for large strings. – Lars Udengaard Mar 24 '13 at 07:31
2

Another options is to use String.Remove

 modifiedText = text.Remove(text.LastIndexOf(separator));

With some error checking the code can be extracted to an extension method like:

public static class StringExtensions
{
    public static string RemoveTextAfterLastChar(this string text, char c)
    {
        int lastIndexOfSeparator;

        if (!String.IsNullOrEmpty(text) && 
            ((lastIndexOfSeparator = text.LastIndexOf(c))  > -1))
        {

            return text.Remove(lastIndexOfSeparator);
        }
        else
        {
            return text;
        }
    }
 }

It could be used like:

private static void Main(string[] args)
{
    List<string> inputValues = new List<string>
    {
        @"http://www.ibm.com/test",
        "hello/test",
        "//",
        "SomethingElseWithoutDelimiter",
        null,
        "     ", //spaces
    };

    foreach (var str in inputValues)
    {
        Console.WriteLine("\"{0}\" ==> \"{1}\"", str, str.RemoveTextAfterLastChar('/'));
    }
}

Output:

"http://www.ibm.com/test" ==> "http://www.ibm.com"
"hello/test" ==> "hello"
"//" ==> "/"
"SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter"
"" ==> ""
"     " ==> "     "
Habib
  • 219,104
  • 29
  • 407
  • 436
0

On C# 8 and newer, you can also use the range operator. Example:

    string oldStr = "hello/test";
    int index = oldStr.LastIndexOf('/');

    if (index != -1)
        string newStr = oldStr[..index];