【问题标题】:Generate fixed length Strings filled with whitespaces生成用空格填充的固定长度字符串
【发布时间】:2012-11-08 15:34:47
【问题描述】:

我需要生成固定长度的字符串来生成基于字符位置的文件。缺少的字符必须用空格字符填充。

例如,CITY 字段的固定长度为 15 个字符。对于输入“芝加哥”和“里约热内卢”,输出是

“芝加哥”
“里约热内卢”

【问题讨论】:

    标签: java string formatting


    【解决方案1】:

    从 Java 1.5 开始,我们可以使用方法java.lang.String.format(String, Object...) 并使用类似 printf 的格式。

    格式字符串"%1$15s" 完成这项工作。其中1$表示参数索引,s表示参数是String,15表示String的最小宽度。 把它们放在一起:"%1$15s"

    我们有一个通用的方法:

    public static String fixedLengthString(String string, int length) {
        return String.format("%1$"+length+ "s", string);
    }
    

    也许有人可以建议另一种格式字符串来用特定字符填充空格?

    【讨论】:

    • Maybe someone can suggest another format string to fill the empty spaces with an specific character? - 看看我给出的答案。
    • 根据docs.oracle.com/javase/tutorial/essential/io/formatting.html1$表示参数索引,15表示宽度
    • 这不会限制字符串的长度为 15。如果它更长,生成的输出也会超过 15
    • @misterti a string.substring 会将其限制为 15 个字符。最好的问候
    • 我应该提到这一点,是的。但我评论的重点是警告输出可能比预期的长,这可能是固定长度字段的问题
    【解决方案2】:

    利用String.format 的空格填充并将它们替换为所需的字符。

    String toPad = "Apple";
    String padded = String.format("%8s", toPad).replace(' ', '0');
    System.out.println(padded);
    

    打印000Apple


    更新更高性能的版本(因为它不依赖于String.format),空格没有问题(感谢 Rafael Borja 的提示)。

    int width = 10;
    char fill = '0';
    
    String toPad = "New York";
    String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
    System.out.println(padded);
    

    打印00New York

    但需要添加检查以防止尝试创建负长度的 char 数组。

    【讨论】:

    • 更新的代码效果很好。这就是我所期望的@thanks mike
    【解决方案3】:

    此代码将具有给定数量的字符;右侧填充空格或截断:

    private String leftpad(String text, int length) {
        return String.format("%" + length + "." + length + "s", text);
    }
    
    private String rightpad(String text, int length) {
        return String.format("%-" + length + "." + length + "s", text);
    }
    

    【讨论】:

      【解决方案4】:

      对于右垫,您需要String.format("%0$-15s", str)

      - 符号将“右”填充,没有 - 符号将“左”填充

      看我的例子:

      import java.util.Scanner;
       
      public class Solution {
       
          public static void main(String[] args) {
                  Scanner sc=new Scanner(System.in);
                  System.out.println("================================");
                  for(int i=0;i<3;i++)
                  {
                      String s1=sc.nextLine();
                      
                      
                      Scanner line = new Scanner( s1);
                      line=line.useDelimiter(" ");
                     
                      String language = line.next();
                      int mark = line.nextInt();;
                      
                      System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
                      
                  }
                  System.out.println("================================");
       
          }
      }
      

      输入必须是字符串和数字

      示例输入:Google 1

      【讨论】:

        【解决方案5】:

        你也可以像下面这样写一个简单的方法

        public static String padString(String str, int leng) {
                for (int i = str.length(); i <= leng; i++)
                    str += " ";
                return str;
            }
        

        【讨论】:

        • 这绝对不是最高效的答案。由于字符串在 Java 中是不可变的,因此您实际上是在内存中生成 N 个长度等于 str.length+1 的新字符串,因此非常浪费。更好的解决方案是只执行一个字符串连接,而不管输入字符串的长度如何,并在 for 循环中使用 StringBuilder 或其他更有效的字符串连接方式。
        • @anon58192932 从 Java 9 开始,情况似乎并非如此,openjdk.java.net/jeps/280dzone.com/articles/…
        【解决方案6】:
        import org.apache.commons.lang3.StringUtils;
        
        String stringToPad = "10";
        int maxPadLength = 10;
        String paddingCharacter = " ";
        
        StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
        

        比番石榴 imo 好得多。从未见过使用 Guava 的单个企业 Java 项目,但 Apache String Utils 非常普遍。

        【讨论】:

          【解决方案7】:

          Guava LibraryStrings.padStart 可以完全满足您的需求,以及许多其他有用的实用程序。

          【讨论】:

            【解决方案8】:
            String.format("%15s",s) // pads right
            String.format("%-15s",s) // pads left
            

            精彩总结here

            【讨论】:

            • 翻转。 String.format("%-15s",s) // 向右填充。 s="HAMBURGER" 为您提供“HAMBURGERbbbbbb”,其中“b” = 空格。链接中的内容显示了示例,String s1 = String.format("{%20s}", "Hello Format");并声明输出是{ Hello Format},我同意。剩下一个垫子了。
            【解决方案9】:

            这是一个巧妙的技巧:

            // 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();
              }
            }
            

            【讨论】:

              【解决方案10】:

              这是带有测试用例的代码;):

              @Test
              public void testNullStringShouldReturnStringWithSpaces() throws Exception {
                  String fixedString = writeAtFixedLength(null, 5);
                  assertEquals(fixedString, "     ");
              }
              
              @Test
              public void testEmptyStringReturnStringWithSpaces() throws Exception {
                  String fixedString = writeAtFixedLength("", 5);
                  assertEquals(fixedString, "     ");
              }
              
              @Test
              public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
                  String fixedString = writeAtFixedLength("aa", 5);
                  assertEquals(fixedString, "aa   ");
              }
              
              @Test
              public void testLongStringShouldBeCut() throws Exception {
                  String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
                  assertEquals(fixedString, "aaaaa");
              }
              
              
              private String writeAtFixedLength(String pString, int lenght) {
                  if (pString != null && !pString.isEmpty()){
                      return getStringAtFixedLength(pString, lenght);
                  }else{
                      return completeWithWhiteSpaces("", lenght);
                  }
              }
              
              private String getStringAtFixedLength(String pString, int lenght) {
                  if(lenght < pString.length()){
                      return pString.substring(0, lenght);
                  }else{
                      return completeWithWhiteSpaces(pString, lenght - pString.length());
                  }
              }
              
              private String completeWithWhiteSpaces(String pString, int lenght) {
                  for (int i=0; i<lenght; i++)
                      pString += " ";
                  return pString;
              }
              

              我喜欢 TDD ;)

              【讨论】:

                【解决方案11】:

                这段代码很好用。

                  String ItemNameSpacing = new String(new char[10 - masterPojos.get(i).getName().length()]).replace('\0', ' ');
                  printData +=  masterPojos.get(i).getName()+ "" + ItemNameSpacing + ":   " + masterPojos.get(i).getItemQty() +" "+ masterPojos.get(i).getItemMeasure() + "\n";
                

                编码愉快!!

                【讨论】:

                  【解决方案12】:

                  Apache common lang3 依赖的 StringUtils 用于解决 Left/Right Padding

                  Apache.common.lang3 提供了StringUtils 类,您可以在其中使用以下方法使用您喜欢的字符进行左填充。

                  StringUtils.leftPad(final String str, final int size, final char padChar);
                  

                  这里,这是一个静态方法和参数

                  1. str - 字符串需要填充(可以为空)
                  2. size - 填充到的尺寸
                  3. padChar 要填充的字符

                  我们在 StringUtils 类中还有其他方法。

                  1. 右键盘
                  2. 重复
                  3. 不同的连接方法

                  我只是在此处添加 Gradle 依赖项供您参考。

                      implementation 'org.apache.commons:commons-lang3:3.12.0'
                  

                  https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.12.0

                  请查看该类的所有 utils 方法。

                  https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

                  GUAVA 库依赖

                  这是来自 jricher 的答案。 Guava 库有 Strings.padStart 可以完全满足您的需求,以及许多其他有用的实用程序。

                  【讨论】:

                    【解决方案13】:
                    public static String padString(String word, int length) {
                        String newWord = word;
                        for(int count = word.length(); count < length; count++) {
                            newWord = " " + newWord;
                        }
                        return newWord;
                    }
                    

                    【讨论】:

                      【解决方案14】:

                      这个简单的功能对我有用:

                      public static String leftPad(String string, int length, String pad) {
                            return pad.repeat(length - string.length()) + string;
                          }
                      

                      调用:

                      String s = leftPad(myString, 10, "0");
                      

                      【讨论】:

                        【解决方案15】:
                        public class Solution {
                            public static void main(String[] args) {
                                Scanner sc = new Scanner(System.in);
                                for (int i = 0; i < 3; i++) {
                                    int s;
                                    String s1 = sc.next();
                                    int x = sc.nextInt();
                                    System.out.printf("%-15s%03d\n", s1, x);
                                    // %-15s -->pads right,%15s-->pads left
                                }
                            }
                        }
                        

                        使用printf() 来简单地格式化输出而不使用任何库。

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 2013-12-17
                          • 2016-01-31
                          • 1970-01-01
                          • 2023-03-15
                          • 1970-01-01
                          • 2015-02-14
                          • 2021-03-15
                          相关资源
                          最近更新 更多