Reputation: 29
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.
Upvotes: 2
Views: 12296
Reputation:
You can use this.
String stringWithoutNull = stringWithNull.replaceAll("null", "");
Upvotes: 0
Reputation: 523
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", "");
Upvotes: 0
Reputation: 10863
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= "";
Upvotes: 4
Reputation: 285405
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 = "";
Upvotes: 3