Right justifing strings

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
rich
Posts: 81
Joined: 19 November 2015, 12:23 PM

Right justifing strings

Post 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
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: Right justifing strings

Post 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.
- Don Kinzer
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Post 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.
- Don Kinzer
rich
Posts: 81
Joined: 19 November 2015, 12:23 PM

Post by rich »

Thanks i will go at it.

cheers,
Richard
Post Reply