简体   繁体   English

如何生成具有可变数量的空格的字符串,或者如何在字符串后不添加空格

[英]how to generate string with varying number of spaces OR how to add no of spaces after a string

I need help to generate empty string with particular no of spaces. 我需要帮助来生成带有特定空格的空字符串。

I tried this, 我试过了

String opCode=  " ";

for(int l=0;l<opCodelen;l++)
{
    opCode+= " " ;   
}
//opCodelen will get change every time

This worked but I want better solution.becoz using this I will have to use multiple loops for multiple columns.Is there any other way to do this? 这行得通,但我想要更好的解决方案.becoz使用它,我将不得不对多个列使用多个循环,还有其他方法吗?

Try String.format() 试试String.format()

    int opCodelen = 5;
    String opCode = String.format("%" + opCodelen + "s", "");
    System.out.println("[" + opCode + "]");

output 输出

[     ]

Another way (uglier but for many probably simpler) to solve it could be 解决它的另一种方法(较丑陋,但对于许多可能更简单)可能是

  • creating array of characters with same length as number of spaces you want to end up with, 创建长度与要结尾的空格数相同长度的字符数组,
  • filling it with spaces 用空格填充
  • and passing it as argument in String constructor. 并将其作为参数传递给String构造函数。

Something like 就像是

char[] arr = new char[10]; // lets say length of string should be 10
Arrays.fill(arr, ' ');     // fill array with spaces
String mySpaceString = new String(arr);
System.out.println(">" + mySpaceString + "<");

output: 输出:

>          <

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM