Generate fixed length Strings filled with whitespaces

后端 未结 13 988
借酒劲吻你
借酒劲吻你 2020-12-04 13:52

I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.

As an example, the fi

13条回答
  •  盖世英雄少女心
    2020-12-04 14:25

    Here's a neat trick:

    // E.g pad("sss","00000000"); should deliver "00000sss".
    public static String pad(String string, String pad) {
      /*
       * Add the pad to the left of string then take as many characters from the right 
       * that is the same length as the pad.
       * This would normally mean starting my substring at 
       * pad.length() + string.length() - pad.length() but obviously the pad.length()'s 
       * cancel.
       *
       * 00000000sss
       *    ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
       */
      return (pad + string).substring(string.length());
    }
    
    public static void main(String[] args) throws InterruptedException {
      try {
        System.out.println("Pad 'Hello' with '          ' produces: '"+pad("Hello","          ")+"'");
        // Prints: Pad 'Hello' with '          ' produces: '     Hello'
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    

提交回复
热议问题