Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add whitespace before a string

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?

like image 561
99maas Avatar asked Jul 24 '15 11:07

99maas


4 Answers

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>);

like image 67
CoderNeji Avatar answered Oct 11 '22 03:10

CoderNeji


String newStr = String.format("%10s", str);
like image 39
Gaurav Mahawar Avatar answered Oct 11 '22 02:10

Gaurav Mahawar


String str = "Hello Word!!";
String.format("%1$" + (10 + str.length()) + "s", str);

Result:

|          Hello Word!!|

10 whitespaces added

like image 31
cahen Avatar answered Oct 11 '22 03:10

cahen


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();
    }
like image 43
Zeeshan Avatar answered Oct 11 '22 02:10

Zeeshan