字符串和StringBuffer

问题描述 投票:1回答:3

我有一个方法,我想返回一个字符串示例的路径,如果我输入:xxdrrryy - 它应该返回rrr,我只能返回一个长度为3的字符串,所以我尝试这个,但我跟踪。必须连续三次出现一封信

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
}
java string stringbuffer
3个回答
2
投票

除非你有特殊原因,否则我建议使用正则表达式。

这样的事情应该足够了

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

只需导入java.util.regex.*


2
投票

请更新您的说明,很难理解您要说的内容。但据我所知,你想要找出字符串中特定字符的计数。假设您输入“aabbbcccc”然后它应该返回c有4个字符或类似的东西。

如果是这种情况,则对该字符串中的每个字符进行简单遍历并将其添加到HashTable中,并在每次找到该字符时增加计数,并返回所需的值。

我希望这对你有帮助。


2
投票

这段代码有效。试试这个:

public static 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
}
© www.soinside.com 2019 - 2024. All rights reserved.