This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Padding strings to valid length Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Padding strings to valid length" Watch "Padding strings to valid length" New topic

Padding strings to valid length

Bill Raterink

Joined: Sep 03, 2003
Posts: 29
Is there a way to force 1) a string to be a certain length, & 2) if there is a ",1" or a ",2" they MUST be in the last 2 positions. In VB it would be similar to this:
TxtStr = left(txtStr & Space(40),40) then tack the ,1 or ,2 on the end.
Please don't stone me for the VB, I'm trying very hard to learn java. ; )
Thanks. -Bill.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Hi, Bill -
We only throw rubber stones here. They don't hurt!
The only way I know to do what you want is to create a StringBuffer with the required size. If you need a String object instead of a StringBuffer, then invoke the StringBuffer object's toString() method to return a String object.
(Hmm. My theory isn't working! The toString() method interprets the first null character as the end of the string. I hope someone else out there can help us both!)
Hope that helps!
And welcome to Java.
[ November 04, 2003: Message edited by: Jeff Bosch ]

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Hi Bill,
Combine Jeff's idea, please try the follow method,
it create a StringBuffer, pad the content to a
desired size, then call toString() to return a String
that is aligned to right.

not so smart guy still curious to learn new stuff every now and then
Bill Raterink

Joined: Sep 03, 2003
Posts: 29
Jeff/chi, Thanks for the help. Now that I think about it, a string BUFFER sounds like what I should be using ANYWAY. In COBOL (forgive me) a buffer implied I/O, which is what I'm after. Of course, objects hadn't been invented yet. We thought object was just unreadable code. HA!HA! Thanks again, -Bill.
Don't get me started about those stupid light bulbs.
subject: Padding strings to valid length
It's not a secret anymore!