Take the 2-minute tour ×

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.

share|improve this question
Post your code and perhaps someone can help. –  bmargulies Sep 8 '12 at 13:53
add comment

3 Answers

up vote 1 down vote accepted
String str = "0101010101110";
char[] cs = str.toCharArray();
    if (cs[i] == '1')
        cs[i] = '0';
    else if (cs[i] == '0')
        cs[i] = '1';
str = new String(cs);
share|improve this answer
thank you very much worked great –  Chris Hawkes Sep 8 '12 at 14:15
add comment
String s = "01101110010".replace("0", "*").replace("1", "0").replace("*", "1");
share|improve this answer
add comment

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"));
share|improve this answer
add comment

Your Answer


