Reputation: 3
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 1
s or 0
s
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.
Upvotes: 0
Views: 2773
Reputation: 117665
String s = "01101110010".replace("0", "*").replace("1", "0").replace("*", "1");
Upvotes: 1
Reputation: 1447
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);
Upvotes: 1
Reputation: 159854
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"));
Upvotes: 1