字符串替换问题

我想将"01110"替换成"01111",要求是取出"01110"中最后那一位的"0",将其替换成"1",结果是"01111",高手请指教

情况1:
如果确定在最后这个位置,
String old = "01110";
String n = old.substring(0, old.length() - 1) + "1";

情况2:
如果不在最后位置
String old = "11110111";
int pos = old.lastIndexOf("0");
String n = old;
if(pos > -1){
n = old.substring(0, pos) + "1" + (pos < old.length() - 1?old.substring(pos + 1) : "");
}

你觉得哪里有难度??
String a = "01110";
a = "01111";

a.substring(0, index) + "1" + a.substring(index + 1)

1、
[code="java"]
int index = 1;//第几个0,start at 0
String old = "011101110";
int i = -1, pos = -2;
while(i < index && pos != -1){
pos = old.indexOf("0", pos == -2 ? 0 : pos + 1);
if(pos > -1){
++i;
}
}
String n = "not found";
if(i == index){
n = old.substring(0, pos) + 1 + (pos < old.length() -1 ? old.substring(pos + 1, old.length()) : "")
}
[/code]

public String relay(String s, int index){
long old=Long.paseLong(s);
return ""+(1L << index | old);
}

public String XX(String s, int start, int end){
return s.subString(0,start-1)+~Long.parseLong(s.subString(start,end))+s.subString(end));

}

修改下mkey的,start,end就不判定边界和顺寻了
[code="java"]String sub = s.substring(start, end);
String a = Long.toBinaryString(~Long.parseLong(sub, 2));
return (start>0?s.substring(0, start-1) : "") + a.substring(a.length() + start - end) + s.substring(end);
[/code]

楼主学过编程吗

你觉着那段代码逻辑合适就自己整个函数,有点同意qinglangee,要是这样的话,建议系统学习下

以下是一个方法
[code="java"]public String genXX(String old, int index){
//int index = 1;//第几个0,start at 0

//String old = "011101110";

int i = -1, pos = -2;

while(i < index && pos != -1){

pos = old.indexOf("0", pos == -2 ? 0 : pos + 1);

if(pos > -1){

++i;

}

}

String n = "not found";

if(i == index){

n = old.substring(0, pos) + 1 + (pos < old.length() -1 ? old.substring(pos + 1, old.length()) : "")

}

}[/code]

上面忘了加return

[code="java"]public String genXX(String old, int index){

//int index = 1;//第几个0,start at 0

//String old = "011101110";

int i = -1, pos = -2;

while(i < index && pos != -1){

pos = old.indexOf("0", pos == -2 ? 0 : pos + 1);

if(pos > -1){

++i;

}

}

String n = "not found";

if(i == index){

n = old.substring(0, pos) + 1 + (pos < old.length() -1 ? old.substring(pos + 1, old.length()) : "")

}

return n;

} [/code]