1

I have a UTF-16LE encoded string that comes from a server. I would like to print that string in Textview of my activity. However, the string prints with spaces in between them. So, "Hello" prints as "H e l l o" and doesn't look all that nice in my screen.

Any help is appreciated.

Thanks

Gentoo
  • 347
  • 2
  • 8
  • 16
  • How are you receiving it? Just dumping a UTF-16LE byte stream into a String would result in the kind of output you are seeing. – Jens Feb 07 '12 at 09:01
  • Yes, that is what I am doing. How would I convert it ? – Gentoo Feb 07 '12 at 13:49

1 Answers1

4

Assuming you have a stream (or array of bytes) containing a UTF-16LE encoded string.

String str0 = "Hello, I am a UTF-16LE encoded String";
byte[] utf16le = str.getBytes("UTF-16LE");

If you do not convert these back & stating the character set used you will be producing a string containing a lot of 0-bytes (UTF-16LE is, obviously, 16-bit) in your resulting String.

String wrong = new String(utf16le); // This will produce crap with \0:s in it.
String correct = new String(utf16le, "UTF-16LE"); // This will be the actual string.

Note: If you dump crap String:s like these into a TextView in ICS it will remove the garbage for you and not print "H e l l o".

Jens
  • 16,853
  • 4
  • 55
  • 52
  • On the second line of your first paragraph of code. You call the getBytes() function on an variable named "str" shouldn't that be "str0" ? – Olli Apr 09 '21 at 12:39