Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mmmdreg

macrumors 65816
Original poster
Apr 14, 2002
1,393
0
Sydney, Australia
How do you fill an 8character string with a string plus a certain character to finish it off?

eg. fooxxxxx, georgexxx, macsxxxx, monkeyxx.

I remember doing it before but can't remember how.. :(

Cheers,

George
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
Code:
public static String padString(String inputString, char padding, int length)
{
StringBuffer toReturn = new StringBuffer(inputString);
while (toReturn.length()<length)
{
toReturn.append(padding);
}
return toReturn.toString();
}
 

Jasonbot

macrumors 68020
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
robbieduncan said:
Code:
public static String padString(String inputString, char padding, int length)
{
StringBuffer toReturn = new StringBuffer(inputString);
while (toReturn.length()<length)
{
toReturn.append(padding);
}
return toReturn.toString();
}

Or you could use robbieduncan's method...
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
Or you could use robbieduncan's method...

Which I haven't tested :eek: I just typed it into the reply box. If I was wanting to do this then that's how I'd implement it though. Should be about as efficient as it can be and is flexible enough.

I wasn't sure what the intended behaviour should be if the string is longer than length though so I left that unaltered. I'd imagine that it should trim the string to be a maximum of length characters long but maybe not?

Edit to add: there is a more efficient option if you are going to call this lots (thousands at least) of times. That would be to pre-generate some padding strings of various lengths (say 2,4,8,16) and use them to call append less. This would only be worth it if: 1) the character you pad with doesn't change much (or at all) 2) you are padding short strings into big lengths a lot (otherwise the lookup costs to get the best padding string would probably outweigh the additional times round the loop)
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
OK I am trying to put of doing actual stuff! So I decided to test my theory about caching the padding being faster. The attached java file (zipped) lets you test this. My findings are: for 8 character strings it's a bit faster, for 40 character strings the caching methods takes around 1/3 of the time!

Have fun and don't submit this as your homework :D
 

Attachments

  • StringPadding.java.zip
    991 bytes · Views: 85
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.