老师布置的一个作业~~ 有兴趣的做下
自己写方法实现replace的功能~
本来以为很简单 偶用String 截出前半部分和后半部分然后连接起来 ~但做起来真的很麻烦~
---没办法了 看看这边有没高手 帮帮忙~ 谢 啊 ~~
自己写方法实现replace的功能~
本来以为很简单 偶用String 截出前半部分和后半部分然后连接起来 ~但做起来真的很麻烦~
---没办法了 看看这边有没高手 帮帮忙~ 谢 啊 ~~
解决方案 »
- 咨询一个设计模式的问题------GUI事件处理机制中的
- 求关于字符串的优秀算法....欢迎参与!
- 银行返回值监听问题
- 怎么将客户端和服务器端写到一个程序中
- 请问怎么求n!的阶层
- 请用正则表达式找出不是csdn的其他单词和数字,一定要用正则表达式才行。
- 新手上路: 接口是不能实例化的,那这个是什么意思?
- 如何把一个Vector 的内容付给另一个Vector?
- 我用的是oracle jDeveloper 9.03,怎样把jdk1.3升为1.4?
- FutureTask类的handlePossibleCancellationInterrupt方法到底是干什么的?
- 郁闷~自考教材找不到学校给的电子文档让我们学习,马上要考试了求个JAVA最基础的试题,谢谢~~
- Java中String.replace()时的正则表达式不会写了, :(
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */ while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}参考一下~~
还有 是写 public String replace(String oldC, String newC) 参数是两个String类的 那个方法
要看懂这个得先看懂 Pattern 和 Matcher 两个类的的五六千代码。
public static String replaceStr(String str, String problemStr, String replace){ for(int i=str.lastIndexOf(problemStr); i>=0; i=str.lastIndexOf(problemStr, i-1)){ if(i==0){ str = replace+str.substring(i+1, str.length()); } else{ str = str.substring(0, i)+replace+str.substring(i+1, str.length()); }//end if }//end for return str; }
}
String str = "123aa123aaa123bbb123ccc123ddd123aa123";
System.out.println(str);
System.out.println(replace(str, "123", "***"));
}
public static String replace(String str, String old, String replacement) {
StringBuffer sb = new StringBuffer();
int index = str.indexOf(old);
if(index < 0) {
return str;
}
int start = 0;
int len = old.length();
do {
sb.append(str.substring(start, index))
.append(replacement);
start = index + len;
index = str.indexOf(old, start);
} while (index >= 0);
sb.append(str.substring(start));
return sb.toString();
}
}
String str = "123aa123aaa123bbb123ccc123ddd123aa123";
String old = "123", snew = "***";
String fw = "";
int index = -1;
while((index=str.indexOf(old))!= -1){
fw += str.substring(0,index) + snew ;
str = str.substring(index +old.length(),str.length()); } String res = fw+str; System.out.println(str); System.out.println(res);
}
}