I am writing an Xor method that ecnrypts some string, adding (like xor operators) random values to its characters. The result should look like a string with hexadecimal values of encrypted characters.
Example:
"Hello world" => "0006F 00046 00066 00076 0004D 0007F 00047 0007D 00062 0006E"
Code:
StringBuilder sb = new StringBuilder();
inputText.chars()
.filter(c -> c != ' ')
.map(c -> c ^ random.nextInt(randBound))
.boxed()
.map(i -> String.format("%05X ", i & 0xFFFFF))
.forEach(sb::append);
if (sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
As you can see, I generated the result as "%05X "
, so I got unwanted space at the end of the line. And you need to use sb.deleteCharAt(sb.length() - 1);
.
How to format the correct result directly in the stream?
source
share