wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Truncating/ Padding a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Truncating/ Padding a string" Watch "Truncating/ Padding a string" New topic
Author

Truncating/ Padding a string

marcus conway
Greenhorn

Joined: Oct 30, 2008
Posts: 12
Hey,

I'm having some trouble creating a method (in the form.....
)

that positions string s in a field of a desired width. If the string is longer than the desired field width, it will need to be truncated. If it is shorter than the desired field width it will need to be padded with blank characters. The alignment parameter determines whether the string will be left aligned ('L' or 'l') in the field (padding added to the right) or right aligned ('R' or 'r') in the field (padding added to the left). And if there are not enough spaces to display the string, at least one space must be provided on the appropriate side.

I've been playing around with it:



And I've been testing it in various ways. But ultimately the I/O should look similar to this:


I've been struggling with this for quite some time now, so any help would be greatly appreciated.

Thanks,

n
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

I think it might be helpful for you to describe the steps you want to follow (your algorithm) in English before trying to code it in Java. Once you have the logical steps clear, it will be much easier to code.

For example, you might say something like this:
1) Determine whether the String will fit in the given space.
2) If it will fit, then...
3) If it will not fit, then...
etc.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Of course, you are not allowed to use String.format ?


[My Blog]
All roads lead to JavaRanch
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Originally posted by Christophe Verre:
Of course, you are not allowed to use String.format ?


Or, it might be better still to use a StringBuilder.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Truncating/ Padding a string