4

Is there a way to remove the characters in a string after the last occurrence of a delimiter?

I have looked into the following questions.

Split string by last separator - In this case, the characters before the last occurrence are omitted. But I just need the opposite of this.

Remove last characters from a string in C#. An elegant way? - Here the characters after the first occurrence of the delimiter are removed.

For e.g. I have a string

"D:\dir1\subdir1\subdir11\subdir111\file1.txt"

The result I expect is

"D:\dir1\subdir1\subdir11\subdir111"

Note: This is just an example. I need a solution to work in other cases too.

Community
  • 1
  • 1
kakkarot
  • 478
  • 1
  • 9
  • 24

3 Answers3

6

You can use the String.Remove() method.

string test = @"D:\dir1\subdir1\subdir11\subdir111\file1.txt";
string result = test.Remove (test.LastIndexOf ('\\'));

The value stored in result will be

"D:\dir1\subdir1\subdir11\subdir111"
kakkarot
  • 478
  • 1
  • 9
  • 24
Karthik S
  • 106
  • 1
  • 6
2

You can easily achieve this using LastIndexOf

string str =@"D:\dir1\subdir1\subdir11\subdir111\file1.txt"
str= str.SubString(0,str.LastIndexOf("\\"));

If you are looking for something generic then create extension method

public static string GetStringBeforeLastIndex(this string str,string delimeter)
{
  return str.SubString(0,str.LastIndexOf(delimeter));
}

Now you just have to call the method

string str =@"D:\dir1\subdir1\subdir11\subdir111\file1.txt"
    str = str.GetStringBeforeLastIndex("\\"); you can pass any delimeter

 string str =@"asdd-asdasd-sdfsdf-hfghfg"
        str = str.GetStringBeforeLastIndex("-");
Viru
  • 2,228
  • 2
  • 17
  • 28
1

this should be the safest way

string Pathname = @"D:\dir1\subdir1\subdir11\subdir111\file1.txt";
string Result = Path.GetDirectoryName(Pathname);
fubo
  • 44,811
  • 17
  • 103
  • 137
  • 1
    that was just an example (file path). i would like the solution to work for any string. i.e i can have a string like "edfe-fefe-geer-edew". the result must be "edfe-fefe-geer- – kakkarot Feb 16 '16 at 11:28
  • @madmax There's no `'\'` in the above example – CinCout Feb 16 '16 at 11:31