More Java questions..

Discussion in 'Mac Programming' started by mmmdreg, Mar 20, 2007.

  1. macrumors 65816

    mmmdreg

    Joined:
    Apr 14, 2002
    Location:
    Sydney, Australia
    #1
    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
     
  2. macrumors 68020

    Jasonbot

    Joined:
    Aug 15, 2006
    Location:
    The Rainbow Nation RSA
    #2
    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.
     
  3. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #3
    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();
    }
    
     
  4. macrumors 68020

    Jasonbot

    Joined:
    Aug 15, 2006
    Location:
    The Rainbow Nation RSA
    #4
    Or you could use robbieduncan's method...
     
  5. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    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)
     
  6. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #6
    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
     

    Attached Files:

Share This Page