Replace and create a string in VB.NET

In this VB tip, we'll show you a quick and easy way to replace a string within a string by using the Replace method of a String object and create a string that consists of the repeated character.

Have you ever needed to replace a portion of a string and generate a string that consists of a repeated character in VB.NET? If so, we'll show you how easy it is to replace a string within a string by using the Replace method of a String object.

In Listing A, we define three variables: strFull to hold the full line of text, strOriginal to hold the word that we want to find and replace, and strReplace to hold the string, which will replace the strOriginalin the strFull. The Replace method of the string is utilized to replace a specified value with the new value in the strFull. The method accepts two parameters: the original string and the string that should replace it. The result is an updated value in the strFull string.

String creation with a repeated character

In order to generate a string that consists of the same character, we overload a String object constructor. The String creation can accept two parameters: a character that needs to be repeated and the number of times the character should be repeated. View Listing B to see example code.

While there are alternatives to this method, it's a very simple and quick way to define a string consisting of a repeated character. Another way to do this would be to create a loop to keep adding one character at a time, but this method results in a much slower performance.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks

Free Newsletters, In your Inbox