Ad

Replace Part Of A String Using 0,1 Instead Of " "

- 1 answer

    mSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSwitch.getText().equals("Everybody")) {
                PRIVACY = PRIVACY.replace(PRIVACY.substring(0, 1), "E");
                Log.d("TEXT", PRIVACY);
            } else if (mSwitch.getText().equals("Nobody")) {
                PRIVACY = PRIVACY.replace(PRIVACY.substring(0, 1), "N");
                Log.d("TEXT", PRIVACY);
            }
        }
    });

Privacy string = "E/E/N/N/E......../N

I have multiple Buttons for changing each Char

It's just a random Chars separated by "/"

So on click of the Toggle Button, I want to replace one of the Chars with either E or N but this above code I'm replacing everything like the result is either E/E/E/E/E.... or N/N/N/N/N...

Where have I gone wrong?

Ad

Answer

This line:

PRIVACY = PRIVACY.replace(PRIVACY.substring(0, 1), "E")

is replacing inside PRIVACY every occurrence of whatever the 1st char is with "E",
because the 1st parameter of the replace() method is the string to find.
Do it like this:

mSwitch.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mSwitch.getText().equals("Everybody")) {
            PRIVACY = "E" + PRIVACY.substring(1);
            Log.d("TEXT", PRIVACY);
        } else if (mSwitch.getText().equals("Nobody")) {
            PRIVACY = "N" + PRIVACY.substring(1);
            Log.d("TEXT", PRIVACY);
        }
    }
});

PRIVACY.substring(1) is the part of PRIVACY beginning from the 2nd char until its end.
Edit
If you want to replace the 5th char with say "A":

PRIVACY = PRIVACY.substring(0, 5) + "A" + PRIVACY.substring(6);

See more substring()

Ad
source: stackoverflow.com
Ad