简体   繁体   中英

java: how to implement replaceAll method of StringBuilder

I implemented the replaceAll() method with matcher, which replaces all punctuations with "". But it always throws an exception: " java.lang.StringIndexOutOfBoundsException: String index out of range: 6 "

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.,.")));
}

If you are going to change the StringBuilder (especially its length by removing characters) inside of the loop, you are going to need to get a new Matcher (because the old one will continue to look at the original buffer or an inconsistent mix of both).

Take a look at how Jon Skeet would do it .

I would assume this to do the trick

private static void filterPunctuation(StringBuilder sb)
{
    int l=sb.length();
    for (int i=0; i<l; i++) if (sb.charAt(i)=='.') sb.deleteCharAt(l--);
}

No need to return it as you are working on the same reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM