Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2655

How can I replace a word at a specific index while returning the whole string?

I'm looking to replace a specific word in my program with a repetition asterixes.

Here is my current function: Word is the word being replaced.

mystring = tbText.text
mystring = Replace(mystring, word, "***", 5, 1)

The issue here is the fact that mystring returns just the replaced word rather than returning the entire string, reasoning for this being, the word at index 5 and ending in index 10 is only being returned due to the minimum index and maximum index set.

Is there another function I can use to replace the specific word while returning the entire string with the word replaced?

Upvotes: 0

Views: 3592

Answers (4)

Grim
Grim

Reputation: 672

Take off the 4th and 5th parameters.

mystring = tbText.text
mystring = Replace(mystring, word, "***")

UPDATE: Having done my research properly, what the OP wants is to change the 4th parameter to 1, like so;

mystring = Replace(mystring, word, "***", 1, 1)

As the documentation explains, this will return the original string starting from position 1 (parameter 4) and only make 1 replacement (parameter 5).

Hopefully we can now all agree that the OPs requirements are satisfied - even though it's many years later!

Upvotes: 1

Gargo
Gargo

Reputation: 711

You can use the StringBuilder Class for this

Dim mystring As String = "This is my String"
Dim word As String = "my"

Dim sb As New System.Text.StringBuilder(mystring)
sb.Replace(word, "***", 8, 2)
Dim newstring As String = sb.ToString()

Now newstring is set to This is *** String

Upvotes: 0

tezzo
tezzo

Reputation: 11115

I think I never used a Start parameter different from 0 so I never noticed that "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."

Try this code to solve your problem:

Dim strWord As String = "6"
Dim strNewWord As String = "*****"

Dim strTest As String = "1234567890"

MsgBox(Strings.Left(strTest, strTest.IndexOf(strWord)) & _
    Replace(strTest, strWord, strNewWord, strTest.IndexOf(strWord) + 1, 1))

Upvotes: 0

jjaskulowski
jjaskulowski

Reputation: 2574

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Replace first occurrence of pattern in a string

Upvotes: 1

Related Questions