remove last word in label split by \

Viewed 30097

Ok i have a string where i want to remove the last word split by \

for example:

string name ="kak\kdk\dd\ddew\cxz\"

now i want to remove the last word so that i get a new value for name as

name= "kak\kdk\dd\ddew\"

is there an easy way to do this

thanks

11 Answers

How do you get this string in the first place? I assume you know that '' is the escape character in C#. However, you should get far by using

name = name.TrimEnd('\\').Remove(name.LastIndexOf('\\') + 1);
string result = string.Join("\\",
            "kak\\kdk\\dd\\ddew\\cxz\\"
            .Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)
            .Reverse()
            .Skip(1)
            .Reverse()
            .ToArray()) + "\\";

Here's a non-regex manner of doing it.

string newstring = name.SubString(0, name.SubString(0, name.length - 1).LastIndexOf('\\'));

This regex replacement should do the trick:

name = Regex.Replace(name, @"\\[a-z]*\\$", "\\");

Try this:

const string separator = "\\";
string name = @"kak\kdk\dd\ddew\cxz\";
string[] names = name.Split(separator.ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(separator, names, 0, names.Length - 1) + separator;

EDIT:I just noticed that name.Substring(0,x) is equivalent to name.Remove(x), so I've changed my answer to reflect that.

In a single line:

name = name = name.Remove(name.Remove(name.Length - 1).LastIndexOf('\\') + 1);


If you want to understand it, here's how it might be written out (overly) verbosely:

string nameWithoutLastSlash = name.Remove(name.Length - 1);
int positionOfNewLastSlash = nameWithoutLastSlash.LastIndexOf('\\') + 1;
string desiredSubstringOfName = name.Remove(positionOfNewLastSlash);
name = desiredSubstringOfName;
string name ="kak\kdk\dd\ddew\cxz\"
string newstr = name.TrimEnd(@"\")

if you working with paths:

  string name = @"kak\kdk\dd\ddew\cxz\"; 
  Path.GetDirectoryName(name.TrimEnd('\\'));
  //ouput: kak\kdk\dd\ddew
string[] temp = name.Split('\\');
string last = "\\" + temp.Last();
string target = name.Replace(last, "");

For Linq-lovers: With later C# versions you can use SkipLast together with Split and string.Join:

var input = @"kak\kdk\dd\ddew\cxz\";
string result = string.Join( @"\", input
                        .Split( @"\", StringSplitOptions.RemoveEmptyEntries )
                        .SkipLast( 1 ))
                + @"\";
Related