我用matcher實現了replaceAll()方法,它用「」替換了所有的標點符號。但它總是會拋出一個異常:「java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:6」java:如何實現StringBuilder的replaceAll方法
private static StringBuilder filterPunctuation(StringBuilder sb){
Pattern pattern = Pattern.compile("(\\.)");
Matcher matcher = pattern.matcher(sb);
while(matcher.find()){
sb.replace(matcher.start(), matcher.end(), "");
// if sb.replace(matcher.start(),matcher.end()," "), it wil be right, but I want replace all punction with ""
}
return sb;
}
public static void main(String[] args){
System.out.println(filterPunctuation(new StringBuilder("test.,.")));
}
你爲什麼不在這裏展示你的實現? – noMAD 2012-04-23 04:19:25
你爲什麼要那樣做?爲什麼不使用那裏的API呢?或者是這個「家庭作業」,在這種情況下,請添加標籤請 – Bohemian 2012-04-23 04:20:05
@Bohemian:沒有替換所有的StringBuilder(當然,通過字符串,我猜沒有失去很多)。 – Thilo 2012-04-23 04:23:58