2

I have this string "nullRobert Luongo 431-232-1233 Canada"

and I'd like to get rid of the null character. I don't know how it got there, but I would like to get rid of it.

IceKing
  • 29
  • 1
  • 1
  • 5

4 Answers4

4

It's likely that you get it because you did something like this:

String s = null;
.
.
.
s+="Robert Luongo 431-232-1233 Canada"; //mind the +=

One way to correctly do it is by:

String s= "";
adhg
  • 10,437
  • 12
  • 58
  • 94
3

You're concatenating a String that is null -- don't do that. Initialize the String at least with ""

So rather than

String myString;

When you do this and later do:

myString += "something";

you'll get `nullsomething

So instead assign an empty String to the String of interest when you declare it.

String myString = "";
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Option 1: Recommended

I would suggest you to look into the issue from where the string is contains 'null' and fix it at the source rather than using hacks.

Option 2: Not recommended

But still if you want to replace the null from it then you can use the following. But it is not recommended as it can replace a proper word containing 'null' in it and make the string junk.

The following replaces the first instance of 'null' with empty String.

string.replace("null", "");

You can also replace all the instances of 'null' with empty String using replaceAll.

string.replaceAll("null", "");
Parth Satra
  • 513
  • 2
  • 16
0

You can use this.

String stringWithoutNull = stringWithNull.replaceAll("null", "");