Home  >  Article  >  Java  >  A case of implementing String.padLeft and String.padRight in Java

A case of implementing String.padLeft and String.padRight in Java

黄舟
黄舟Original
2017-09-16 10:03:122583browse

本篇文章主要介绍了Java中实现String.padLeft和String.padRight,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

因为习惯了C#中的padLeft和padRight,接触Java后突然失去这两个功能,觉得别扭,就试着实现了这两个方法。

Java中String.format()中带有字符串对齐功能如下:


System.out.println(String.format("*%1$-10s*", "moon"));
System.out.println(String.format("*%1$10s*", "moon"));

输出:

以上方法经过简单的变换可以得到:


public static String padWhitespaceLeft(String s, int len) {
  return String.format("%1$" + len + "s", s);
}

public static String padWhitespaceRight(String s, int len) {
  return String.format("%1$-" + len + "s", s);
}

调用下面方法:


System.out.println("*" + padWhitespaceLeft("moon", 12) + "*");
System.out.println("*" + padWhitespaceRight("moon", 12) + "*");

可以得到结果:

以上只是介绍左右对齐时,补空白符的方法,但是在实际开发过程中,单纯的补空白符也许满足不了开发要求,为此我还要做一次强化改进:


  /**
   * @作者 尧
   * @功能 String左对齐
   */
  public static String padLeft(String src, int len, char ch) {
    int diff = len - src.length();
    if (diff <= 0) {
      return src;
    }

    char[] charr = new char[len];
    System.arraycopy(src.toCharArray(), 0, charr, 0, src.length());
    for (int i = src.length(); i < len; i++) {
      charr[i] = ch;
    }
    return new String(charr);
  }
  /**
   * @作者 尧
   * @功能 String右对齐
   */
  public static String padRight(String src, int len, char ch) {
    int diff = len - src.length();
    if (diff <= 0) {
      return src;
    }

    char[] charr = new char[len];
    System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());
    for (int i = 0; i < diff; i++) {
      charr[i] = ch;
    }
    return new String(charr);
  }

调用方法如下:


System.out.println("*" + padLeft("moon", 12, &#39;-&#39;) + "*");
System.out.println("*" + padRight("moon", 12, &#39;-&#39;) + "*");

输出结果:

这样在Java中处理字符串对齐就可以像C#那样简单了。

效率也是有保障的。

The above is the detailed content of A case of implementing String.padLeft and String.padRight in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn