0

it has been 8 years since I last programmed, and then it was just basics for a networking degree. I am writing a basic program to start my way back into java programming. the program is dealing with binary numbers stored as strings.

e.g. 01101110010

I have got everything else working, but now I want to swap all "1" for "0" and all "0" for "1"

to get 10010001101

The problem is the only way I know to swap chars is to create a new string with the chars replaced but I can only do one char at a time and then I just end up with a string of all 1s or 0s

so I thought about using a char array and trying to swap each char in the array but I have no idea how to go about this.

1
  • Post your code and perhaps someone can help. Commented Sep 8, 2012 at 13:53

3 Answers 3

1
String str = "0101010101110";
char[] cs = str.toCharArray();
for (int i = 0; i < cs.length; i++)
{
    if (cs[i] == '1')
        cs[i] = '0';
    else if (cs[i] == '0')
        cs[i] = '1';
}
str = new String(cs);
Sign up to request clarification or add additional context in comments.

Comments

1

If the method you use is open you could use String.replace():

String str = "01101110010";
System.out.println(str.replace("1", "X").replace("0", "1").replace("X", "0"));

Comments

1
String s = "01101110010".replace("0", "*").replace("1", "0").replace("*", "1");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.