有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中使用制表符格式化字符串和字符串数组

我有一个赋值,其中我应该有一个方法,该方法将String对象数组格式化,以某种方式用一个标题制表,并将所有对象(格式化后)很好地放入一个String中,以便该方法返回。这个方法在一个对象类中,所以它最终将以相同的方式格式化多个对象,所以我需要它以相同的方式格式化不同的String长度

以下是我需要的输出:

      Hashtags:
                #firstHashtag
                #secondHashtag

每个标签都在String[]个标签中

即。 String[] hashtags = ["#firstHashtag", "#secondHashtag"]

所以基本上我需要使用string.format()在包含一个选项卡式“Hashtags:”头的单个字符串上创建,然后“Hashtags”数组中的每个字符串都在一个新行上,并使用双选项卡。“hashtag”数组的大小会发生变化,因为它位于对象类中

谁能帮我用一下绳子吗。格式化程序

到目前为止,我的方法是这样的:

public String getHashtags()
     {
          String returnString = "Hashtags:";
          String add;
          int count = 0;

          while(count < hashtags.length)
          {
               //hashtags is an array of String objects with an unknown size

               returnString += "\n";
               add = String.format("%-25s", hashtags[count]);

               //here I'm trying to use .format, but it doesn't tabulate, and I 
               //don't understand how to make it tabulate!!
               count++;
               returnString = returnString + add;
          }

          if(hashtags == null)
          {
               returnString = null;
          }

          return returnString;

     }

如果您有任何关于如何设置格式的有用建议,我们将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    你的绳子。format()语句将创建一个左对齐并填充到25个空格的字符串。例如,这一行:

    System.out.println("left-justified  >" + String.format("%-25s", "hello") + "<");
    

    产出:

    left-justified  >hello                    <
    

    另一件事是,你没有真正使用制表符(我在你的程序中没有看到制表符字符)。一串format()正在创建长度为25且左对齐的字符串。在创建返回字符串时请记住这一点。此外,每次循环都会添加一个换行符。这就是为什么你会得到多行输出