I am trying to replace a single character (bit) in a string, which is a binary number. For bit replacement i have designed a method, which simply partition the string using string.substring() method accoring to the given index then concatenates all. Below is the method-
/*
*Method will replace the index-th bit with bitToInsert in the given str
*/
String str = "11000110100110011111";
int index = 5;
int bitToInsert = 0;
if (index == 0) {
str = str.substring(0, str.length() - 1) + bitToInsert;
} else {
str = str.substring(0, str.length() - index - 1) + bitToInsert + str.substring(str.length() - index);
}
This works fine, however this takes very much time to replace a bit, when given str is very large. Is there any other way, so that replacement of any bit can be done in much less time compare to the above method?
If you use
StringBufferinstead ofStringyou can do this: