Java 将整数转换为等效数量的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2635076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:08:30  来源:igfitidea点击:

Convert integer to equivalent number of blank spaces

javastring-formatting

提问by mike

I was wondering what the easiest way is to convert an integer to the equivalent number of blank spaces. I need it for the spaces between nodes when printing a binary search tree. I tried this

我想知道最简单的方法是将整数转换为等效数量的空格。打印二叉搜索树时,我需要它作为节点之间的空间。我试过这个

  int position = printNode.getPosition(); 
  String formatter = "%1"+position+"s%2$s\n";
  System.out.format(formatter, "", node.element);

But I am getting almost 3 times as many spaces compared to the int value of position. I'm not really sure if I am formatting the string right either. Any suggestions would be great! If it makes it clearer, say position = 6; I want 6 blank spaces printed before my node element.

但是与位置的 int 值相比,我得到的空间几乎是原来的 3 倍。我也不确定我是否正确格式化了字符串。任何建议都会很棒!如果它更清楚,请说 position = 6; 我想在我的节点元素之前打印 6 个空格。

采纳答案by Eyal Schneider

I think you meant something like:

我想你的意思是这样的:

    int n = 6;
    String s = String.format("%1$"+n+"s", "");


System.out.format("[%13s]%n", "");  // prints "[             ]" (13 spaces)
System.out.format("[%1s]%n", ""); // prints "[   ]" (3 spaces)

回答by Oak

Why not loop over the integer and add a space on each iteration?

为什么不循环遍历整数并在每次迭代时添加一个空格?

String spaces = "";
for (int i = 0 ; i < position ; i++) spaces += " ";

And you can use StringBuilderinstead of String, if positionmight get very big and performance is an issue.

StringBuilder如果position可能会变得非常大并且性能是一个问题,您可以使用代替字符串。

回答by polygenelubricants

You can create a char[]of the desired length, Arrays.fillit with spaces, and then create a Stringout of it (or just appendto your own StringBuilderetc).

您可以创建char[]所需长度的 a ,Arrays.fill它带有空格,然后从中创建一个String(或仅创建append您自己的StringBuilder等)。

import java.util.Arrays;

int n = 6;
char[] spaces = new char[n];
Arrays.fill(spaces, ' ');
System.out.println(new String(spaces) + "!");
// prints "      !"

If you're doing this with a lot of possible values of n, instead of creating and filling new char[n]every time, you can create just one long enough string of spaces and take shorter substringas needed.

如果您使用 的许多可能值来执行此操作n,则无需new char[n]每次都创建和填充,您可以只创建一个足够长的空格字符串并substring根据需要缩短。

回答by Sylar

Straight foward solution:

直接解决方案:

int count = 20;

StringBuilder sb = new StringBuilder(count);
for (int i=0; i < count; i++){
 sb.append(" ");
}
String s = sb.toString();

StringBuilder is efficient in terms of speed.

StringBuilder 在速度方面是高效的。

回答by Martijn Courteaux

This is an easy, but rubbish, way:

这是一种简单但很垃圾的方法:

 int count = 20;
 String spaces = String.format("%"+count+"s", "");

or filled in

或填写

String spaces = String.format("%20s", "");

回答by Gui

Here's an example:

下面是一个例子:

public class NestedLoop {
public static void main (String [] args) {
  int userNum  = 0;
  int i = 0;
  int j = 0;


  while (i<=userNum) {
     System.out.println(i);
     ++i;
     if (i<=userNum) {
     for (j=0;j<i;j++) {
        System.out.print(" ");  
     }
    } 
   }
  return;
  }
}

If we make userNum = 3, the output would be:

如果我们让 userNum = 3,输出将是:

0
 1
  2
   3

Hope it would help!

希望它会有所帮助!

回答by Bill K

If one were going to use an iterative solution anyway, one might want to do it a more "Groovy" way, like:

如果无论如何都打算使用迭代解决方案,那么人们可能希望以一种更“Groovy”的方式来实现,例如:

def spaces=6
print ((1..spaces).collect(" ").join())

Note that this doesn't work for zero spaces. for that you might want something more like:

请注意,这不适用于零空格。为此,您可能想要更像:

print (spaces?(1..spaces).collect(" ").join():"")

回答by Subu

//This prints the spaces according to the number in the variable n. So in this case it will print 15 spaces.

//这将根据变量n中的数字打印空格。所以在这种情况下,它将打印 15 个空格。

int n=15;

整数 n=15;

System.out.format("%1$"+n+"s", "");

System.out.format("%1$"+n+"s", "");