Sandah Aung
Sandah Aung

Reputation: 6188

How to remove nul characters (\0) from string in Java

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?

Upvotes: 17

Views: 20792

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201429

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

Upvotes: 3

ruakh
ruakh

Reputation: 183251

You can write:

mText.replace("\0", "");

Upvotes: 39

Related Questions