Page 1 of 1

Right justifing strings

Posted: 05 December 2018, 17:05 PM
by rich
Hello:

I need help in using the string functions.

I convert an integer to a string { Cstr() } and now want to right justify it into a field to display on an LCD.

Any hints on doing that would be appreciated.

Thank you
Richard

Re: Right justifing strings

Posted: 05 December 2018, 18:58 PM
by dkinzer
rich wrote:I [...] want to right justify [a string' into a field to display on an LCD.
Perhaps the most straightforward way, though not particularly time or memory efficient, is this:

Code: Select all

str = Right("    " & CStr(ival), 5)
This works by adding four spaces to the beginning of the digit string and then extracting the rightmost five characters.

I say that this isn't particularly memory or time efficient because it involves several memory allocations. With more work you could copy the characters of the string equivalent of the integer to the rightmost positions of a byte array that was initialized with spaces and then create a new string from that array. I would say, however, that it probably isn't worth the extra work in most cases to go to the trouble of doing this.

Posted: 05 December 2018, 19:03 PM
by dkinzer
As an added note, if you anticipate dealing with negative values you'll need to prepend five spaces and then extract the rightmost six characters. This supports the range of values from -32768 to 32767. With a little extra work (left as an exercise for the reader) you can add a plus sign for positive values. The same strategy can be applied for Long values as well as for unsigned values.

Posted: 06 December 2018, 5:43 AM
by rich
Thanks i will go at it.

cheers,
Richard