I am currently programming a multi-player game, and I am working on the networking side of it all right now. I have a packet system set up, and the way it works (with Strings at least) is that it takes a number of characters to a maximum of "X" characters. The characters are converted to bytes for sending to the server. If there are less than X characters, then the remaining bytes are set to 0. The issue is that when processing this information on the server and converting it to a string, the 0-byte characters are a '□' in my console, and invisible in my JTextPane. How can I remove all of these 0-byte characters from the String in a clean way? I'd prefer not to have another loop and more variables just to remove the 0-bytes before converting to a String. No one likes dirty-looking code. :p
Packet Data:
03100101118000000000971001091051100000000
- 03 = Packet ID (irrelevant)
- 100101118000000000 = Username ("dev")
- 971001091051100000000 = Password ("admin")
Resulting String:
- usernameString = "dev□□□□□□□□□"
- passwordString = "admin□□□□□□□"
What I've tried:
usernameString.replaceAll(new String(new byte[] {0}, "UTF-8"), "");
passwordString.replaceAll(new String(new byte[] {0}, "UTF-8"), "");
However, this did not change the String at all.
0StandardCharsets.UTF_8constant instead of"UTF-8"literal. This is faster and you will not need to handle/rethrowUnsupportedEncodingException.StandardCharsets.UTF_8was compared to the"UTF-8"literal. Thanks a ton.