Pad Middle of string with zeros

  • Thread starter Thread starter Ben
  • Start date Start date
B

Ben

Hi

I have a string which is at least 4 characters but can be more which I need
to pad, with zeros, to a full length of 15 after the 3rd charactor.

Eg '1234' to '123000000000004'

How can I do this?

Also how can I truncate this back to 4 or however many charactors (e.g.
123000000000400 = 123400)

Any help will be much appreciated

Thanks
B
 
Ben said:
Hi

I have a string which is at least 4 characters but can be more which I need
to pad, with zeros, to a full length of 15 after the 3rd charactor.

Eg '1234' to '123000000000004'

How can I do this?

1. split the string into "123" and "4" (check out String.Substring())
2. pad the second string (check out String.PadLeft())
3. concatenate the two string (check out String.Concat())

Also how can I truncate this back to 4 or however many charactors (e.g.
123000000000400 = 123400)

remove the 4th character from your string (check out String.Remove()) while
it equals "0" (while loop with String.Equals()).

If you want to improve your knowledge on algorithms, i suggest the books by
Robert Sedgewick.
 
Diana,

Diana Mueller said:
3. concatenate the two string (check out String.Concat())

I suggest to use the '&' operator for string concatenation instead of using
'String.Concat'.
If you want to improve your knowledge on algorithms, i suggest the books
by
Robert Sedgewick.

Full ACK!
 
Diana,

Diana Mueller said:
Why is that preferable?

Readability is better when using '&':

\\\
Dim s As String =
"Hello " & Name & "," & ControlChars.NewLine
///

vs.

\\\
Dim s As String = _
String.Concat("Hello ", Name, ",", ControlChars.NewLine)
///
 
Diana,
In addition to readability as Herfried suggests, the & operator will
concatenate any constants at compile time. String.Concat is strictly a
runtime function.

Const format As String = "Hello" & ControlChars.NewLine & "World"

When dealing with Object variables (parameters really) & Option Strict On
String.Concat is useful:

Option Strict On
Dim i1 As Object = 1
Dim f1 As Object = 1.0F
Dim d1 As Object = 100D
Dim s1 As Object = "help"

Debug.WriteLine(i1 & f1 & d1 & s1)
Debug.WriteLine(String.Concat(i1, f1, d1, s1))

The first statement is a compile error, while the second succeeds, both
should return the same result! As String.Concat is overloaded for both
String & Object!

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top