如何使用输入将一个字符串中的5个字符准确地放置并隔开

时间:2018-09-12 17:21:02

标签: java string printf spacing

基本上,我试图在Java中编写一个要输入5个字母的代码,例如“ Hello”。代码需要吐出一个输出,每个字母之间要相隔十个间距。我还必须使用printf并使用%隔开它们。我可以通过使用.replace而不使用%来做到这一点,但是那不是我应该做的。 因此输出应为: 你好

Scanner scanner = new Scanner(System.in);
System.out.println("Enter five chatracters: ");
String charoutput = scanner.next();
String charoutput2 = charoutput.replace("", "       ");

System.out.println("You have entered: " +charoutput2);

2 个答案:

答案 0 :(得分:1)

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter five chatracters: ");

    // You can include validation of the length of the input line if necessary
    String answer = scanner.next();
    String[] charArr = answer.substring(0, 5).split("");
    String result = Arrays.stream(charArr)
            .map(p -> String.format("%s%10s", p, ""))
            .collect(Collectors.joining());

    System.out.println(result);
    scanner.close();

答案 1 :(得分:0)

使用String inputString = "1+3,432.123*4535-24.4"; int stringLength = inputString.length(); String[] destArray = new String[stringLength]; int destArrayCount = 0; String currentString = ""; for (int i=0; i<stringLength; i++) { //check it's ascii value if its between 0 (48) and 9 (57) if(inputString.charAt(i) >= 48 && inputString.charAt(i) <= 57 ) { currentString += inputString.charAt(i); } else { destArray[destArrayCount++] = currentString; currentString = ""; //we know we don't have a number at i so its a non-number character, add it destArray[destArrayCount++] = "" + inputString.charAt(i); } } //add the last remaining number destArray[destArrayCount++] = currentString; for(int i = 0; i < destArrayCount; i++) { System.out.println("(" + i + "): " + destArray[i]); } %的解决方案

printf