x


Remove the last word from a string

Is there some code like this:

var newStr = str.Substring(0, str.length-1);

That will allow you to remove the last whole word instead of one character?

more ▼

asked Jul 09 '10 at 12:55 PM

Ben gravatar image

Ben
374 25 25 28

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

This should do it:

var newStr = str.Replace("yourWord", "");

Edit:

var newStr : String;
var idx = str.LastIndexOf(" ");
if (idx > -1)
    newStr = str.Remove(idx);
else
    newStr = str;
more ▼

answered Jul 09 '10 at 12:56 PM

Mike 3 gravatar image

Mike 3
30.5k 10 65 253

Thanks, but I need the code to be generic so that it removes the last word no matter what the word is. Also, the word might be found more than once in a string and I wouldn't want to remove them all!

Jul 09 '10 at 01:23 PM Ben

In that case i'm editing the question and then my answer so it makes more sense

Jul 09 '10 at 01:33 PM Mike 3

LastIndexOf(" "); is just what I was looking for! Thanks

Jul 09 '10 at 09:40 PM Ben
(comments are locked)
10|3000 characters needed characters left

Given your comment to Mike, here's a solution.

Use Remove along with LastIndexOf(" "), to get the index of the last space. We will need more information from you if finding a space isn't a good enough solution for you to find the final word.

more ▼

answered Jul 09 '10 at 01:32 PM

Jessy gravatar image

Jessy
15.6k 72 95 196

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x419
x91
x8

asked: Jul 09 '10 at 12:55 PM

Seen: 3345 times

Last Updated: Jul 09 '10 at 01:33 PM