I'm writing a Xor method which ecnrypts some string by adding (as xor operation) random values to its characters. Result should look like as string with hex values of encrypted characters.
Example:
"Hello world" => "0006F 00046 00066 00076 0004D 0007F 00047 0007D 00062 0006E"
The code:
StringBuilder sb = new StringBuilder();
inputText.chars() // get char stream
.filter(c -> c != ' ') // remove spaces
.map(c -> c ^ random.nextInt(randBound)) // do xor for each char
.boxed() // to Integer stream
.map(i -> String.format("%05X ", i & 0xFFFFF)) // to Hex String values
.forEach(sb::append);
if (sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
As you see, I've formated the result as "%05X ", so I've got unwanted space in the end of string. And need to use sb.deleteCharAt(sb.length() - 1);.
How to format the correct result directly in stream?