Generate fixed length Strings filled with whitespaces

后端 未结 13 1002
借酒劲吻你
借酒劲吻你 2020-12-04 13:52

I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.

As an example, the fi

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 14:20

    For right pad you need String.format("%0$-15s", str)

    i.e. - sign will "right" pad and no - sign will "left" pad

    See my example:

    import java.util.Scanner;
     
    public class Solution {
     
        public static void main(String[] args) {
                Scanner sc=new Scanner(System.in);
                System.out.println("================================");
                for(int i=0;i<3;i++)
                {
                    String s1=sc.nextLine();
                    
                    
                    Scanner line = new Scanner( s1);
                    line=line.useDelimiter(" ");
                   
                    String language = line.next();
                    int mark = line.nextInt();;
                    
                    System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
                    
                }
                System.out.println("================================");
     
        }
    }
    

    The input must be a string and a number

    example input : Google 1

提交回复
热议问题