【问题标题】:newline character indenting? (Java)换行符缩进? (爪哇)
【发布时间】:2012-08-28 08:27:46
【问题描述】:

我正在尝试使用 \n 创建一个字符串列表,但每当我添加多个字符串时,字符串都会缩进到前一个字符串的位置,因此示例输出为:

0 hello nain
            1 test nain
                       2 huh nain

我不知道它为什么这样做。这是我创建字符串的代码:

            String[] posts = currentTopic.getMessages("main");
            //String[] postsOutput = new String[posts.length];
            String postsOutput = "0 " + posts[0];

            for(int i = 1; i < posts.length; i++){
                postsOutput += "\n" + i + " " + posts[i];
                //postsOutput[i] = i + posts[i];
            }

            sc.close();
            return postsOutput;

我也尝试将 \n 移动到附加的末尾,但结果仍然相同。任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 使用System.getProperty("line.separator") 代替换行符。
  • 顺便说一下,不要在字符串后面加上'+'运算符。使用 StringBuffer 或 StringBuilder,尤其是在循环中...您的代码将生成许多无用的对象(String 的实例)
  • 不要使用StringBuffer,它不同步。

标签: java string newline indentation


【解决方案1】:

看起来您在一个“\n”刚刚停止(换行)并且您缺少所需的回车符的系统上。

这不应该是你应该关心的事情:line.separator 属性正在调整到主机操作系统,因此它的行为类似于System.out.println

【讨论】:

  • +1。 @nain33 可以使用\r\n。 CR + 低频。 ASCII 上的字符 13 和 10。
  • 应该有一些与 Java 操作系统无关的变量可以适应这种情况,不是吗?
  • 使用System.getProperty("line.separator")
  • @Alex:是的,刚刚想通了^_^
  • 你也可以试试BufferedWriter。它有一个newLine 方法。无论如何,它使用System.getProperty("line.separator") @Alex 指出:)
【解决方案2】:

试试\r\n,即回车换行。

【讨论】:

    【解决方案3】:

    我认为这是使用String.format 的一个很好的例子,因为%n 总是使用系统特定的行分隔符。在你的循环里面写:

    postsOutput += String.format("%n%d %d", i, posts[i]);
    

    【讨论】:

      【解决方案4】:

      您应该使用属性System.getProperty("line.separator"),它包含底层系统换行符。

      String newline = System.getProperty("line.separator");
      String[] posts = currentTopic.getMessages("main");
      //String[] postsOutput = new String[posts.length];
      String postsOutput = "0 " + posts[0];
      
      for(int i = 1; i < posts.length; i++){
          postsOutput += newline  + i + " " + posts[i];
          //postsOutput[i] = i + posts[i];
      }
      
      sc.close();
      return postsOutput;
      

      【讨论】:

        猜你喜欢
        • 2011-06-24
        • 1970-01-01
        • 2016-09-30
        • 2010-11-14
        • 2012-11-01
        • 2013-08-25
        • 1970-01-01
        • 2023-03-04
        相关资源
        最近更新 更多