Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove 0-byte (UTF-8) characters in String

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.

like image 877
TheNewGuy Avatar asked Oct 29 '25 11:10

TheNewGuy


2 Answers

As all of your zeros appear at the end of the string you can solve this even without regular expresions:

static String trimZeros(String str) {
    int pos = str.indexOf(0);
    return pos == -1 ? str : str.substring(0, pos);
}

usernameString = trimZeros(usernameString);
passwordString = trimZeros(passwordString);
like image 107
Tagir Valeev Avatar answered Nov 01 '25 03:11

Tagir Valeev


usernameString = // replace 1 or more \0 at the end of the string
    usernameString.replaceAll("\0+$", "");

\0 is an escape for the Unicode character with a numerical value 0 (sometimes called NUL). In other words:

System.out.println((int) "\0".charAt(0)); // prints 0

What you tried seems to work for me too. (See Ideone example.) Not sure why it doesn't for you. There may be another problem. Make sure you are reassigning the result. ; )

like image 27
Radiodef Avatar answered Nov 01 '25 03:11

Radiodef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!