Replace String At End

D

Derek Hart

What is the best way to replace a string only at the end?

If I have a string such as "abc 123 def 456 abc" - I only want to replace
abc at the end. Is there a way?
 
A

Armin Zingler

Derek said:
What is the best way to replace a string only at the end?

If I have a string such as "abc 123 def 456 abc" - I only want to replace
abc at the end. Is there a way?

dim s = "abc 123 def 456 abc"
dim result = s.substring(0, s.length-3) & "new end"
 
J

Jeff Johnson

What is the best way to replace a string only at the end?

If I have a string such as "abc 123 def 456 abc" - I only want to replace
abc at the end. Is there a way?

If the question is "Is there a built-in Framework method to do this" then
the answer is No.

You could use a regular expression to find all the occurrences of your
pattern and then get the location of the last item in the Matches
collection.

You could also reverse the string (AND the search pattern!) and use
IndexOf() to find the pattern and then between that, the length of the
string, and the length of the search pattern you could determine its
position in the original string.

And then there's the looping way of using IndexOf() to find the pattern and
continuing to use it (with the overload that specifies the start position of
the search) to keep looking until you don't find the pattern anymore. The
last one you find is...duh...the last one in the string.
 
S

Sergey Poberezovskiy

Derek,

Using Regular expressions would be one way to go:

Dim result As String = Regex.Replace("abc 123 def 456 abc", "abc$", "cba")

Then the result will be: "abc 123 def 456 cba"

Hope this helps
 
J

Jeff Johnson

What is the best way to replace a string only at the end?

If I have a string such as "abc 123 def 456 abc" - I only want to replace
abc at the end. Is there a way?

Could you define "at the end"? The other replies seem to assume you mean "at
the VERY END of the string," whereas I interpreted your statement to mean
"the LAST occurrence of the string," meaning that in "abc 123 abc 456 789"
you wanted to replace the second "abc" even though it was not at the
absolute end of the string.

And by the way, this is a basic code question and really has nothing to do
with Windows Forms....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top