String puzzle

Brain teaser

When you enter any string in the console

YamadaTaro //input
a        r
m        a
a        T
d        a
a        d
T        a
a        m
r        a
oraTadamaY

Write the code displayed as above.

The ** "oraTadamaY" ** on the last line seems to have been a reverse method that returns strings in reverse order in the String class or StringBuilder class (remember). You can use this.

Well, the remaining middle part. This means that (string length-2) spaces will be inserted between the characters. This means that the characters extracted by charAt () should be concatenated at both ends of the blank character string group that has been repeatedly combined with the for statement (character string length-2) times.

main.java


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		String a = s.nextLine();

		StringBuilder sb = new StringBuilder(a);
		StringBuilder blank = new StringBuilder();

		int len = a.length();
		for (int i = 0; i < len - 2; i++) {
			blank.append(" ");
		}
		for (int j = 1; j < len - 1; j++) {
			System.out.println(a.charAt(j) + blank.toString() + a.charAt(len - j - 1));
		}
		System.out.println(sb.reverse());
    }
}

Actually I wanted to treat it as the scanned Stinrg, but since I had to use the reverse method, I am converting String to StringBuilder.

I don't want to use for (;;) because the outlook is not so good. I would like to use the extended for or while rather than that, but since it seems that useless local variables will increase, I will use for (;;).

When I think about it now, I feel that I can go with a character array (char []) and an if statement. In that case, the number of lines is likely to be long.

			System.out.println(a.charAt(j) + blank.toString() + a.charAt(len - j - 1));
		}```
 Since the closing price of j is len-1, the index of the rightmost character on the 2nd to 9th lines is {(len-1) -j}. I think ** len-1-j ** is easier to understand than ** (len --j --1)) ** above.


Recommended Posts

String puzzle
String
Java string
String replacement
Liar String
java.lang Summary 2 (String)
String Buffer practice
[Java] String padding
MyBatis string comparison
Java string processing
String class methods
Split string (Java)
Delete any string