Results 1 to 3 of 3
  1. #1
    firewalll is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default Get item from string array and pack with blank space

    here is the string array value:

    String[] regionList
    where
    regionList[0] = "AAA"
    regionList[1] = "BBBB"


    I would like to check all items and change to fix length 4

    that is

    regionList[0] = "AAA "
    regionList[1] = "BBBB"

    How could I get from the string array and add " " to the end of the item?
    :):):):):):)

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    You get the strings from the array using the index notation as you did in your post. Ie

    regionList[0] is the first string in the array
    regionList[1] is the second.

    Since Strings are immutable you will have to replace the string in the array with the padded string.

    You could concatenate the string with a space:

    Java Code:
    regionList[0] = regionList[0] + " ";
    Or you could use StringBuilder which offers an append() method. The most flexible (but complicated) method would be to use the Formatter class.

    Java Code:
    StringBuilder buf = new StringBuilder();
    Formatter formatter = new Formatter(buf);
    regionList[0] = formatter.format("%-4s", regionList[0]).toString();
    System.out.printf("|%s|%n", regionList[0]);
    The format expression "%-4s" means "format to width 4 padding with spaces on the right" as described in the API documentation linked to above.

  3. #3
    firewalll is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default

    The first method is easier to understand. I will implement using this way.
    Thanks pbrockway2

Similar Threads

  1. Extract item from a string
    By firewalll in forum New To Java
    Replies: 2
    Last Post: 09-02-2009, 06:00 AM
  2. Blank space
    By sandy1028 in forum New To Java
    Replies: 1
    Last Post: 04-21-2009, 11:00 AM
  3. Replies: 1
    Last Post: 08-03-2007, 11:52 AM
  4. Print a blank space
    By susan in forum New To Java
    Replies: 2
    Last Post: 07-30-2007, 02:58 PM
  5. visual web pack
    By Jack in forum NetBeans
    Replies: 2
    Last Post: 07-02-2007, 06:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •