Search code examples
javatext-align

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?


Solution

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