Replacing " " with _ in AndroidStudio (Java)

Viewed 143

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;
1 Answers

If your intent is to convert any text to snake_case (or lower_underscore), it can get quite tricky if you consider all edge cases, so using a library might be your best bet.

One useful library on Java for this could be Google Guava's com.google.common.base.CaseFormat. You can see how to get started here: https://github.com/google/guava

You can look at the CaseFormat.LOWER_UNDERSCORE method.


It is possible the issue is with the string using a different whitespace character, in which case you should look into RegEx with the String.replaceAll method, but this is unlikely.

Have you looked at the output the replace method is generating? Are you sure the issue is with the underscore not being replaced and not somewhere else on the svg file name? Which I assume is what you are trying to achieve.

Your second option would only work for countries with exactly 2 words in their name, but there are plenty of countries with more words than that (or single words). Also, it also requires that exactly 1 space character was used, and not any other whitespace characters.

Related