17

I understand that this code in C# is trying to remove nul characters (\0) from a string.

string.Join("", mText.Split(new string[] { "\0" }, StringSplitOptions.None));

Is there any way to do that efficiently in Java?

Sandah Aung
  • 6,156
  • 15
  • 56
  • 98
  • ScaryWombat This string is retrieved from a smart card. Is there any chance `null` might be included? – Sandah Aung Apr 08 '16 at 05:04
  • not sure why this question was downvoted. The upvotes on its answer clearly shows that this question is very relevant. – comiventor Oct 31 '17 at 04:49

2 Answers2

39

You can write:

mText.replace("\0", "");
ruakh
  • 175,680
  • 26
  • 273
  • 307
  • I get the error message "Illegal escape: '\0'" when I try that. Is this new? I'm using Android so perhaps that is the reason. – Tobias Reich Jun 13 '22 at 13:05
  • 1
    @TobiasReich: So strange! The spec seems clear about this -- see https://docs.oracle.com/javase/specs/jls/se18/html/jls-3.html#jls-3.10.7 -- so I wouldn't expect any variation between implementations. But maybe try `\u0000` instead? – ruakh Jun 13 '22 at 17:11
  • Interesting but yes, the \u0000 seems to work. Not sure what's the difference but that does the trick. – Tobias Reich Jun 14 '22 at 08:12
3

In Java 8+ you could use StringJoiner and a lambda expression like

String str = "abc\0def";
StringJoiner joiner = new StringJoiner("");
Stream.of(str.split("\0")).forEach(joiner::add);
System.out.println(str);
System.out.println(joiner);

Output is

abc
abcdef
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249