Replace understanding

Hello,
maybe this is a misunderstanding in how replace works, but why is this code:

dim source as string = "916 099 259&0&"
dim result as string
result= source.Replace(source.NthField("&",2),"new")


returning:
916 new99 259&0&

expected:
916 099 259&new&

i am replacing source.NthField("&",2) which is 0 with “new”, or not?

Marco

The first parameter of Replace is the text you want to replace. You’re telling it to replace “0” with “new”. The first occurrence of 0 is the 099.

Try breaking your statements into multiple lines to make debugging easier.
I avoid nthfield in general.

If you’re trying to replace &0& with &new& you should be more specific with your replace statement. If you’re trying to do anything else, I don’t have enough information to help.

(incorrect guess)

NthField is 1-based because 1995 won’t go away
New documentation link for NthField for those that prefer it

What you are getting is correct.

As per answers above …

source.NthField("&",2) when source = “916 099 259&0&”

gives “0” (ie: the second “0” in source, Nth field starts indexes at 1)

Then, the replace searches and replaces “0” with new, which gives

916 new99 259&0&

(Don’t forget, replace just searches the FIRST occurrence it comes across in the whole string. If you did ReplaceAll instead, you would get

916 new99 259&new&

To get what your expected is, you are going to have to devise search and replace for 2nd occurrence only …

:innocent: I got it

source.NthField("&",2) is 0 and I am replacing this “0” (first occurrence)…

Thanks !

Split the source on &
Change the second element of the Array you got as a result
Then Join them back together

1 Like