Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove last word in label split by \

Tags:

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

like image 560
user175084 Avatar asked Jan 28 '10 15:01

user175084


People also ask

How do I remove the last word of a string in word?

In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character. We can achieve that by calling String's length() method, and subtracting 1 from the result.

How do I remove the last text from a string?

The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb. deleteCharAt(str. length() – 1).

How do you remove the last word of a sentence?

To remove the last word from a string, get the index of the last space in the string, using the lastIndexOf() method. Then use the substring() method to get a portion of the string with the last word removed.

How do you remove the last word in a sentence in Java?

String listOfWords = "This is a sentence"; String[] b = listOfWords. split("\\s+"); String lastWord = b[b. length - 1]; And then getting the rest of the the string by using the remove method to remove the last word from the string.


2 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);
like image 138
Webleeuw Avatar answered Sep 21 '22 18:09

Webleeuw


string result = string.Join("\\",
            "kak\\kdk\\dd\\ddew\\cxz\\"
            .Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)
            .Reverse()
            .Skip(1)
            .Reverse()
            .ToArray()) + "\\";
like image 33
dtb Avatar answered Sep 17 '22 18:09

dtb