build string as repeated character

  • Thread starter Thread starter John A Grandy
  • Start date Start date
J

John A Grandy

what's the best way in VB.NET to build a string as a concatenation of a
certain number of characters ?

for example, 25 "*" characters :

"*************************"
 
John,
I'm not sure what the "best way" is, however VB.NET offers the following
methods:

Dim strC As String

strC= new String("C"c,10) ' New string CCCCCCCCCC

Me.Text = strC

Note if you are using Option Strict On (you are using Option Strict On
correct!), you will need to specify a Char literal as opposed to a String
Literal. A Char literal looks like a String literal only it has a lower case
c on the end.

"A"c is a char literal
"A" is a string literal.

There is also the StrDup function found in the Microsoft.VisualBasic.Strings
module that you can use to create the string.

strC = StrDup(10, "C"c)
strC = StrDup(10, "C")

Dim obj As Object = "C"
obj = StrDup(10, obj)

Which is overloaded for Char, String and Object, so its more forgiving with
Option Strict On. Note the Object overload returns an Object, however the
parameter still needs to contain a String or Char.

Hope this helps
Jay
 
I'm finding that PadRight() doesn't work .... do you know why that is ?

Dim s As String
s = "Some text followed by an underline"
s.PadRight(100-s.Length,"_")

s is returned as "Some text followed by an underline"
 
John,
String is immutable, which means you cannot modify the current instance of
the string, hence, PadRight is a function and not a sub.

Try something like

s = s.PadRight(100-s.Length,"_")

However I suspect you want:

s = s.PadRight(100,"_")

As the length to PadRight is the total length of the string, including
existing characters, not the amount to add to the existing string...

Hope this helps
Jay
 
Back
Top