I have a String which contains a binary value ( 101101 ). now I want to check if the last letter is 1 and if so change it to 0 . how can I do that ?
Asked
Active
Viewed 143 times
-2
-
1What have you already tried, and in what way is this "changing the order" as per your title? – Jon Skeet Aug 15 '12 at 12:16
-
1From what you describe, how is this any different from [this question](http://stackoverflow.com/questions/1660034/replace-last-part-of-string)? – thegrinner Aug 15 '12 at 12:18
5 Answers
6
String result = "101101".substring(0,5) + "0";
why checking? The last character will always be 0, regardless if it was 1 or 0 before...

Andreas Dolk
- 113,398
- 19
- 180
- 268
3
You can write
int i = 0b101101;
if (i & 1 != 0)
i = i & ~1;
or much simpler
i &= ~1; // sets lowest bit to 0.

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
-
1You could also use `i ^= 1`, assuming you keep the `i & 1 != 0` test. – João Silva Aug 15 '12 at 12:24
-
1I think your post is kind of misleading since it looks like you're trying to use the hex literal as a binary literal. – DaoWen Aug 15 '12 at 12:24
-
-
-
2Unfortunately, this doesn't help the O.P. with the `String` he has at the moment. Maybe put this in there before your code: `String s =
; int i = Integer.parseInt(s);` and this after your code: `s = Integer.toString(i);` – Zéychin Aug 15 '12 at 12:35
3
Simple version;
String binary = "101101";
binary = binary.substring(0, binary.length() - 1) + "0";
Example here.

Joachim Isaksson
- 176,943
- 25
- 281
- 294
1
One possible solution:
String k = "101101";
System.out.println(k);
int len = k.length();
char[] charr = k.toCharArray();
if(charr[len - 1] == '1') {
charr[len - 1] = '0';
}
k = new String(charr);
System.out.println(k);

Less
- 3,047
- 3
- 35
- 46
-
2
-
-
2yeah, I also forgot to mention - beside being one possible, this is probably the worst solution to this problem... ever :) – Less Aug 15 '12 at 12:43
-
that was the first post that I saw , now how can I remove the last character ? – Aida E Aug 15 '12 at 12:56
-
@matarsak Why do you want to remove the last character? Everyone has answered your initial question. Are you suggesting that you want something else now? – maba Aug 15 '12 at 13:10