0

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?

Oliver Kucharzewski
  • 2,523
  • 4
  • 27
  • 51

4 Answers4

1

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!

Grim
  • 672
  • 4
  • 17
  • That will replace all instance of word. – jjaskulowski Jul 16 '14 at 12:53
  • The OP isn't exactly clear about whether they want all instances replaced or not. I interpreted it as 'hiding' all the occurrences of the word, since it's being replaced with asterisks. – Grim Jul 16 '14 at 13:34
  • 1
    The original code explains the OP is replacing first instance. – jjaskulowski Jul 16 '14 at 14:40
  • 1
    @doker This has reared it's head nearly 5 years later - can you let me know if we are now in agreement? Hopefully the update will explain how the function works for any future visitors! – Grim Mar 13 '19 at 11:38
1
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Replace first occurrence of pattern in a string

Community
  • 1
  • 1
jjaskulowski
  • 2,524
  • 3
  • 26
  • 36
0

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))
tezzo
  • 10,858
  • 1
  • 25
  • 48
0

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

Gargo
  • 621
  • 6
  • 17