remove last word in label split by \\

2020-08-09 16:59发布

问题:

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

回答1:

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);


回答2:

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


回答3:

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

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


回答4:

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;


回答5:

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;


回答6:

My Solution

 public static string RemoveLastWords(this string input, int numberOfLastWordsToBeRemoved, char delimitter)
        {
            string[] words = input.Split(new[] { delimitter });
            words = words.Reverse().ToArray();
            words = words.Skip(numberOfLastWordsToBeRemoved).ToArray();
            words = words.Reverse().ToArray();
            string output = String.Join(delimitter.ToString(), words);
            return output;
        }

Function call

RemoveLastWords("kak\kdk\dd\ddew\cxz\", 1, '\')


回答7:

This regex replacement should do the trick:

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


回答8:

string name ="kak\kdk\dd\ddew\cxz\"
string newstr = name.TrimEnd(@"\")


回答9:

if you working with paths:

  string name = @"kak\kdk\dd\ddew\cxz\"; 
  Path.GetDirectoryName(name.TrimEnd('\\'));
  //ouput: kak\kdk\dd\ddew


回答10:

string[] temp = name.Split('\\');
string last = "\\" + temp.Last();
string target = name.Replace(last, "");


标签: c#