Java String 使用空格和零左填充字符串

在本教程中,我们将看到如何使用空格和零来填充字符串:

使用空格左填充

class LeftPaddingExample1 {
  public static void main(String[] args) {
    System.out.println("#" + padLeftSpaces("mystring", 10) + "@");
    System.out.println("#" + padLeftSpaces("mystring", 15) + "@");
    System.out.println("#" + padLeftSpaces("mystring", 20) + "@");
  }

  public static String padLeftSpaces(String str, int n) {
    return String.format("%1$" + n + "s", str);
  }
}

输出:

#  [email protected]
#       [email protected]
#            [email protected]

使用零左填充

class LeftPaddingExample2 {
  public static void main(String[] args) {
    System.out.println("#" + padLeftZeros("mystring", 10) + "@");
    System.out.println("#" + padLeftZeros("mystring", 15) + "@");
    System.out.println("#" + padLeftZeros("mystring", 20) + "@");
 }

  public static String padLeftZeros(String str, int n) {
    return String.format("%1$" + n + "s", str).replace(' ', '0');
  }
}

输出:

#[email protected]
#[email protected]
#[email protected]

赞(0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址