Search code examples
javastring-formattingpadding

Java pad string with space


I am attempting to add padding to a string, however I cannot figure out how to do this. My goal is to have something that looks like this:

Home: email@gmail.com (7 spaces after the colon)

The above has "Home:" hardcoded and should have 7 spaces along with a variable for the email. Here is what I have so far:

return String.format("Home:%7s", email);

My understanding was that %7s was to add left padding with a value of 7, then I have the s for the string I want to include after the padding. Can someone help to correct me?

How it looks is much like this:

Home:email@gmail.com

So what's happening is when I have something like this, everything looks fine:

return String.format("Home:%7s", "email");

The second I add my variable rather than hardcoding "email", I lose the padding completely.


Solution

  • Hope this might help

        String email = "abc@jhkj.com";
        System.out.println(String.format("Home:%1$3s%s%s", "", email));
    

    Output: Home: abc@jhkj.com