如"011[color=red]1111[/color]10"红色那段,红色这段数字是不确定的,它可以是"0000",也可以是"1011",总之是不确定的,但索引是知道的,现在要求是当你用传参的方式输入1的时侯,我暂时用"1111"代替,"1111"将会变成"0001",当你输入2的时侯,1111将会变成"0010",当你输入3的时侯,1111将会变成"0100",以此类推,高手请指教
[code="java"]public class Test {
public static String replace(String str, int begin, int end, int no) {
StringBuffer buffer = new StringBuffer();
buffer.append(str.substring(0, begin));
int len = end - begin + 1;
for (int i = 0; i < len; i++) {
if (no == len - i)
buffer.append('1');
else
buffer.append('0');
}
buffer.append(str.substring(end + 1));
return buffer.toString();
}
public static void main(String[] argv) {
for (int i = 1; i <= 4; i++)
System.out.println(replace("011111110", 3, 6, i));
}
}[/code]
[code="java"]
public String replaceStr(String oldstr, int begin,int end, int no){
String[] news = new String[]{"0001","0010","0100"};
return oldstr.substring(0,begin) + news[no - 1] + oldstr.substring(end + 1);
}
[/code]
用运算的方式解决什么?
"1111","1101","0101"等要替换的位跟1运算变成"0001"???
[code="java"]
int a = 2;
String str="",str2="",src="011111110";
while(a>1){
str+=a%2;
a= a/2;
}
str=str+a;
for(int i = str.length()-1; i >= 0;i--)
str2+=str.charAt(i);
for(int i = 0; i<=4-str2.length();i++)
str2="0"+str2;
src = src.substring(0, 3) + str2 + src.substring(7);
System.out.println(src);
[/code]
3是0011,不是0100吧?
public String replaceStr(String oldstr, int begin,int end, int no){
String[] news = new String[]{"0001","0010","0100"};
return oldstr.substring(0,begin) + news[no - 1] + oldstr.substring(end + 1);
}
上面qinglangee 的方法不錯哦 ,簡單明了,顶一个
以下代码应该就是你要的:
public class Test {
public static String replace(String str, int begin, int end, int no) {
StringBuffer buffer = new StringBuffer();
buffer.append(str.substring(0, begin));
int len = end - begin + 1;
for (int i = 0; i < len; i++) {
if (no == len - i)
buffer.append('1');
else
buffer.append('0');
}
buffer.append(str.substring(end + 1));
return buffer.toString();
}
public static void main(String[] argv) {
for (int i = 1; i <= 4; i++)
System.out.println(replace("011111110", 3, 6, i));
}
}
[code="java"]
public class TestAnd {
public static String replace(String a, int begin, int end, int no) {
int b = Integer.parseInt(a.substring(begin, end), 2);
String c = Integer.toBinaryString(b & (int) Math.pow(2, no - 1));
while (c.length() < end - begin + 1) {
c = "0" + c;
}
return a.substring(0, begin) + c + a.substring(end + 1);
}
public static void main(String[] args) {
System.out.println(replace("111111111111", 4, 7, 2));
}
}[/code]