Search code examples
javastringstringbuffer

Strings and StringBuffer


I have a method that I want to return some path of a string example if I input : xxdrrryy - it should return rrr, I can only return a string of length 3, so I am trying this , but I'm stalked . it must be the occurrence of a letter three times consecutively

public String countTriple(String str) {
    int count = 1;
    char currChar = str.charAt(0);
    for(int i=1; i<str.length(); i++) {
        if(currChar == str.charAt(i)) {
            count++;
            if(count == 3) {
                StringBuilder sb = new StringBuilder("");
                for(int j=0; j<3;j++) {
                    sb.append(currChar);
                }
                return sb.toString();
            }
        }
        else {
            count = 1;
        }
        currChar = str.charAt(i);
    }
    return null; //no triple found
}

Solution

  • Unless you have a specific reason not to, I suggest using a regex.

    Something like this should suffice

    Pattern p = Pattern.compile("(\\w)\\1\\1");
    Matcher m = p.matcher("abbccc");
    if(m.find()){
        System.out.println(m.group());
    }
    

    Just import java.util.regex.*