Patrick
Patrick

Reputation: 13

Why is the replace function removing part of my string?

I'm not sure if I'm actually using VB.net. I'm using Visual Basic 2010 express, and I don't know if that's the same thing or not.

I'm using the replace function to replace a 0 at a specific position in a string with lots of 0s with a 1. I'm using the optional parameter that lets you choose where in the string the function starts searching for the character. But whenever it does this, it removes all the parts of the string before the position that I tell it to go to in the string.

So what can I do to make it return the entire string as it was before, but just with that one character changed at that position. The line of code is:

board = Replace(board, "0", "1", position, 1)

Upvotes: 1

Views: 97

Answers (2)

Trevor_G
Trevor_G

Reputation: 1331

For some weird reason String.Replace returns the string FROM position with N replacements.

From MSDN:

The return value of the Replace function is a string that begins at the position specified by Start and concludes at the end of the Expression string, with the substitutions made as specified by the Find and Replace values.

But if you use a StringBuilder:

Dim sb As New StringBuilder(board)
sb = sb.Replace("0", "1", position, 1)
board = sb.ToString

It works as expected.

I have a sneaking suspicion that's a bug from Microsoft that they never fixed because it would impact all the people that were already using it that way.

Upvotes: 4

A Friend
A Friend

Reputation: 2750

There is another method available which does what you need called Mid which you can read more about here.

It is used like so:

Mid(board, position, 1) = "1"

Be aware that "Start is one based"

Upvotes: 0

Related Questions