I need your help in adding whitespace before a string as I need to format the String value to be in a specific position in the page. For example:
System.out.println(" Hello Word!!");
The above will give 10 spaces before the String which I did them manual, but is there any other way to specify the space before the String other than adding manual spaces?
Consider this as your code....
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();
}
This will add desired no of spaces in the string at its beginning...
Just pass your input String
and no of spaces needed....
As addspace(<no_of_spaces>,<input_string>);
String newStr = String.format("%10s", str);
String str = "Hello Word!!";
String.format("%1$" + (10 + str.length()) + "s", str);
Result:
| Hello Word!!|
10 whitespaces added
You can write your own fumction:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With