【问题标题】:How to pad a string with blanks if desired length isn't long enough?如果所需长度不够长,如何用空格填充字符串?
【发布时间】:2016-07-19 04:56:58
【问题描述】:

我正在创建一个存储玩家姓名、等级和技能的随机访问文件,并且我正在制作它,以便如果您输入的玩家姓名超过 26,它会在 26 处被删除,如果它比 26 短,我想用空格填充它。

我想出了 subString 以确保只选择前 26 个,但我想知道如果我没有输入任何值,你们会建议什么来确保我有 26 个填充空白。这只是我的代码的一个sn-p,如果您希望我添加更多,我会的。

public static String PlayerNameMethod (RandomAccessFile store){
    try{
        String PlayerName = input.next();
        store.writeUTF(PlayerName);
        if (PlayerName.length()> 26){
            PlayerName.substring(0,26);
            System.out.print("The Player Name is" + PlayerName);
        }

        if (PlayerName.length()< 26){
            //PART I CANT FIGURE OUT
        }

【问题讨论】:

    标签: java randomaccessfile


    【解决方案1】:

    有很多方法可以做到这一点 - 最直接的一种是循环,您可以在其中添加空格,直到字符串足够长。

    但一种代码非常短并使用内置函数的方法是String.format 函数:

    PlayerName = String.format("%-26s", PlayerName);
    

    请注意,您的其余代码存在一些问题。行:

    PlayerName.substring(0,26);
    

    什么都不做。字符串是不可变的,这意味着改变字符串的函数总是返回新字符串——它们不会修改原来的字符串。

    所以那行应该是:

    PlayerName = PlayerName.substring(0,26);
    

    【讨论】:

      【解决方案2】:

      @Erwin 提到的答案是最简洁的。 但是,如果您想自己做,这就是您需要做的。

         if (PlayerName.length() < 26)
          {
              StringBuilder paddedName = new StringBuilder(PlayerName);
              for (int i = 0; i < 26 - PlayerName.length(); i++)
              {
                  paddedName.append(" ");
              }
              PlayerName = paddedName.toString();
          }
      

      注意:java 约定规定变量名应以小写字母开头。在你的情况下playerName

      【讨论】:

      • OP 想要空白而不是零。而不是for 循环和额外的变量,你可以只做while (paddedName.length() &lt; 26) paddedName.append (' ');
      • @dave_thompson_085,原本打算替换零。
      【解决方案3】:

      创建一个长度=26-PlayerName.length()的字符串,每个字符为空白,并将其附加到PlayerName

      【讨论】:

        猜你喜欢
        • 2012-04-28
        • 2012-11-08
        • 2013-12-17
        • 2016-02-25
        • 2015-11-04
        • 1970-01-01
        • 2018-05-27
        • 1970-01-01
        相关资源
        最近更新 更多