Sunday, March 22, 2009

VB: Left or Right Padding a string.

Lets learn how to padding a string in Visual Basic. I didn't find any built in function like LPad(str, 5), that will take string and padding with 5 fields. The example now I'm providing for padding will only work, if your string length is less than the maximum size after padding.

Lets talk about Left padding with zero ("0"). Lets say you have a string having "123", and now you want to add additional extra 2 zero on the left side. Means 5 field left padding. below is the code.
testString = "123"
output = Right("00000" & testString, 5)
Me.print output

It will print 00123 on the form. How the padding worked? Since you need 5 field padding, I have added 5 zeros with the original string. It will become "00000123". Now using Right function, I have taken the 5 fields from the string from right size, which is "00123". See?? left padded with 2 zeros. If you need to make it 10 fields 0 padding, you'll require to add 10 zeros "0000000000". You can change the padding fields from 0 to any characters.

Using the similar Idea, below is how to do is for Right side padding. Exactly the same idea implemented.
testString = "123"
output = Left("00000" & testString, 5)
Me.print output

Its a tricky way, and I have already told you the drawback of the approach. But it was handy enough to fulfill my requirements when I was facing that circumstance. I still believe there might be a better way to handle that issue.

Thanks once again to reading my article.


Sandhya M said...

Thanks! I used this today in my code.

Anonymous said...

Thanks!!! brilliant. :)

Anonymous said...

Ha! I was 'googling' today to find a solution just like this.

Your idea is BRILLIANT in it's simplicity.

I love simple code like this which solves a major problem.

Well done, well done indeed!

Anonymous said...

splendid! So simple solution. Thanks a lot.

binaenaleyh said...

Thank you for this elegant solution.

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...