我需要你的帮助,在一个字符串前添加空格,因为我需要将该字符串值格式化到页面的特定位置。例如:
System.out.println(" Hello Word!!");
以上代码会在字符串前添加10个手动添加的空格,但是否有其他方式指定字符串前的空格而不是手动添加空格呢?
我需要你的帮助,在一个字符串前添加空格,因为我需要将该字符串值格式化到页面的特定位置。例如:
System.out.println(" Hello Word!!");
以上代码会在字符串前添加10个手动添加的空格,但是否有其他方式指定字符串前的空格而不是手动添加空格呢?
String newStr = String.format("%10s", str);
public static void main(String[] args) {
String hello = "hello";
Brute b = new Brute();
System.out.println( b.addspace(1,hello));
}
String addspace(int i, String str)
{
StringBuilder str1 = new StringBuilder();
for(int j=0;j<i;j++)
{
str1.append(" ");
}
str1.append(str);
return str1.toString();
}
这将在字符串开头添加所需数量的空格...
只需传递您的输入字符串
和所需的空格数....
使用addspace(<no_of_spaces>,<input_string>);
String str = "Hello Word!!";
String.format("%1$" + (10 + str.length()) + "s", str);
结果:
| Hello Word!!|
添加了10个空格
你可以编写自己的函数:
public static void main(String[] args) {
String myString = "Hello Word!!";
System.out.println(getWhiteSpace(10)+myString);
}
private static String getWhiteSpace(int size) {
StringBuilder builder = new StringBuilder(size);
for(int i = 0; i <size ; i++) {
builder.append(' ');
}
return builder.toString();
}
String s = "%s Hellow World!";
StringBuilder builder = new StringBuilder();
for(int i=0;i<10;i++){
builder.append(" ");
}
System.out.println(s.format(s,builder.toString()));
import java.io.*;
import java.util.*;
class spaceBeforeString
{
public static void main(String args[])
{
String str="Hello";
for(int i=0;i<10;i++)
{
str=" "+str;
}
System.out.println(str);
}
}
import java.util.*;
import java.io.*;
class AddSpaceDemo
{
String str;
int noOfSpaces;
Scanner sc=new Scanner(System.in);
void getInput()
{
System.out.println("Enter the string before which the space is to be added: ");
str=sc.next();
System.out.println("Enter the no. of spaces to be added before the string: ");
noOfSpaces=sc.nextInt();
}
String addSpaceBefore()
{
for(int i=0;i<noOfSpaces;i++)
{
str=" "+str;
}
return str;
}
}
class AddSpace
{
public static void main(String args[])
{
String s;
AddSpaceDemo a=new AddSpaceDemo();
a.getInput();
s=a.addSpaceBefore();
System.out.println("String after adding whitespace before string: ");
System.out.println(s);
}
}
int width = 32;
public static void main(String[] args) {
String dash = "--------------------------------";
String item = "COMPANY NAME";
String price = "00.00";
String string = alignment(item, price);
String description = "123-456-7890";
String tax = "0.00";
String string2 = alignment(description, tax);
System.out.println(dash);
System.out.println(string);
System.out.println(string2);
}
private static String alignment(String item, String price) {
String s = "";
s += item;
int x = 0;
while(x < width - item.length() - price.length()) {
s += " ";
x++;
}
s += price;
return s;
}
}
System.out.printf();
方法。 - Codebender