Problem: Hello, I am trying to replace a space within a string in my app using the following code:
String nationality1 = dataSnapshot.child("ean_data").child("nationality1").getValue().toString().toLowerCase();
nationality1 = nationality1.replace(" ", "_");
String svgNationality = "flag_" + nationality1;
Unfortunately, this doesn't work. I have seen a few similar questions that suggest that the " " isn't a regular space but some other kind.
I think the following might work, but it's kind of a roundabout:
String nationality1 = dataSnapshot.child("ean_data").child("nationality 1").getValue().toString().toLowerCase();
String[] parts = nationality1.split(" ");
String part1 = parts[0];
String part2 = parts[1];
String _nationality = part1 + "_" + part2;
In this particular instance, the String is "united states" which I want to become "united_states".
Question: Is there any way to make this work with just .replace? The data is being drawn from firebase btw.
Workaround solution that encompasses strings with more than one space:
String nationality1 = "_" + dataSnapshot.child("ean_data")
.child("nationality 1").getValue().toString().toLowerCase();
if (nationality1.contains(" ")){
nationality1 = nationality1.replaceFirst("_", "");
String[] parts = nationality1.split(" ");
nationality1 = "";
for (int i = 0; i < parts.length; i++){
nationality1 = nationality1 + "_" + parts[i];
}
}
String svgNationality = "flag" + nationality1;