PDA

View Full Version : More Java questions..




mmmdreg
Mar 21, 2007, 12:41 AM
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



Jasonbot
Mar 21, 2007, 01:26 AM
just make it:

string x=x+"xx";

or for simplicity make an array and then loop it in if you want multiple values with the specific ending character.

robbieduncan
Mar 21, 2007, 03:45 AM
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
Mar 21, 2007, 04:10 AM
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
Mar 21, 2007, 04:27 AM
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
Mar 21, 2007, 05:06 AM
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