How To Insert Character / String At Specific Position (Index) In C# And VB.NET

In this post , we will learn how to insert a character or string at certain index of string using C# and VB.NET

C# Insert Character / String At Certain Index Or Position

Create a new empty project in Visual Studio. Choose C# Windows Form as project. In this project , we will need following components:

  • Four TextBox (txtmainstring - for accepting main string , txttext - for accepting character / string to be inserted , txtindex - the index number at which the text will be inserted , txtoutput - to show the final output)
  • One Button (btninsert -Upon clicking on which , insert operation occurs)

Code To Insert Character / String At Custom Index In C#

 private void btninsert_Click(object sender, EventArgs e)
        {
            var themainstring  = txtmainstring.Text;
            var thetext = txttext.Text;
            int theindex = Convert.ToInt32(txtindex.Text);

            var theoutput = themainstring.Insert(theindex, thetext);
        	txtoutput.Text = theoutput;
        }

Output Of C# Character / String Insert At Custom Position / Index


VB.NET Insert Character / String At Certain Index Or Position

Create a new empty project in Visual Studio. Choose VB Windows Form App as project. In this project , we will need following components:

  • Four TextBox (txtmainstring - for accepting main string , txttext - for accepting character / string to be inserted , txtindex - the index number at which the text will be inserted , txtoutput - to show the final output)
  • One Button (btninsert -Upon clicking on which , insert operation occurs)

Code To Insert Character / String At Custom Index In VB.NET

Private Sub btninsert_Click(sender As Object, e As EventArgs) Handles btninsert.Click
        Dim themainstring = txtmainstring.Text
        Dim thetext = txttext.Text
        Dim theindex = txtindex.Text

        Dim theoutput = themainstring.Insert(theindex, thetext)
        txtoutput.Text = theoutput
    End Sub

Output Of VB.NET Character / String Insert At Custom Position / Index


Conclusion

In both c# and vb.net , we have taken <p> element as our main string and used '/' character to be inserted at 1st index. In this way we can insert string or character at certain index in vb.net or c#

FAQ

How To Insert Character At Specific Index In C# And VB.NET

By using Insert function with two parameter (index and character to be inserted) we can insert character at specific index

Is insert only available in C#

The insert function is available in both c# and vb.net which generally takes two parameters