首页 > 解决方案 > 如何在java中运行for循环?

问题描述

我想知道为什么这段代码不运行。有什么遗漏吗?

计算"xx"给定字符串中的个数。我们会说允许重叠,所以"xxx"包含 2 "xx"

public class Drumkit {
    int countXX(String str){
        String a = "abcxxx";
        int count = 0;
        for (int i = 0; i < str.length() - 1; i++) {
            if (a.substring(i, i + 2).equals("xx")) count++;
        }
        return count;
    }
}

标签: java

解决方案


你的问题不清楚。但是,您可以尝试此代码

public static void main(String[] args) {
    final int count = countXX("abcxx efjxx xyzxx xx xxxx xx","xx");
    System.out.println(count);
}

static int countXX(final String text, final String occurrenceOf){
    int count = 0;
    int fromIndex=0;
    for (int i = 0; i < text.length() - 1; i++) {
        int index = text.indexOf(occurrenceOf,fromIndex);
        if(index >-1) {
            count++;
            fromIndex=index+1;
        }
    }
    return count;
}

推荐阅读