jfly
jfly

Reputation: 7990

Simple way to split UTF16 string by NULL

I'm extracting UTF16 strings from a byte array, the strings are separated by one or more NULL(U+0000), when I print the converted string, it trims the NULL automatically, the below example program outputs "WinWin"

import java.nio.charset.Charset;

class Ucs {
    public static void main(String[] args) {
        byte[] b = new byte[] {87, 0, 105, 0, 110, 0, 0, 0, 0, 0, 87, 0, 105, 0, 110, 0, 0, 0}; 
        String s = new String(b, Charset.forName("UTF-16LE"));
        System.out.println(s);
    }   
}

but I want them separated like "Win Win", only if I split s by something. I know I can find the NULL character in a for loop, which is really nasty. Is there a simple way to do this?

Upvotes: 0

Views: 108

Answers (2)

Alexander Heim
Alexander Heim

Reputation: 154

You could use a method called replaceAll(). It´s quite simple to use.

string.replaceAll("<the letter you want to replace>", "");

Mind though that this won´t really increase your performance if that´s what you are looking for.

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 9650

You can use split:

        System.out.println(Arrays.asList(s.split("\\00")));

Upvotes: 2

Related Questions