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
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.
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).
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.
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.
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()) + "\\";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With