How to change one character in a string

Peter Hibbs 101 Reputation points
2021-03-07T11:35:20.28+00:00

Hi All,

I am using VB.NET 2019.

I have a Text box control on a form that holds a string, how can I change one character in that string at a specified position using code? For example, suppose the control holds a string of characters like "ABCDE" and I want to change the character at position 4 to an asterisk so that it would then be "ABC*E".

Peter Hibbs.

Developer technologies Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-03-07T11:42:43.68+00:00

    You can read-modify-write, or try this alternative:

    With TextBox1
        If .TextLength >= 4 Then
            .SelectionStart = 3
            .SelectionLength = 1
            .SelectedText = "*"
        End If
    End With
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Peter Hibbs 101 Reputation points
    2021-03-07T11:57:13.957+00:00

    Hi Viorel-1

    OK, thanks, that works but is this the simplest method to do this? In VBA it can be done with the MID function in one line of code. I would have thought that VB.NET would have something similar, but maybe not! Perhaps it will be possible to build a user defined function which emulates the MID function, I will have to think about it.

    Anyway, thanks again.

    Peter Hibbs.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.