5

2 つの文字列を入力する必要があります。最初の文字列は任意の単語で、2 番目の文字列は前の文字列の一部であり、文字列番号 2 の出現回数を出力する必要があります。たとえば、文字列 1 = CATSATONTHEMAT 文字列 2 = AT です。CATSATONTHEMAT で AT が 3 回発生するため、出力は 3 になります。これが私のコードです:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.next();
    String word9 = sc.next();
    int occurences = word8.indexOf(word9);
    System.out.println(occurences);
}

1このコードを使用すると出力されます。

4

4 に答える 4

11

興味深い解決策:

public static int countOccurrences(String main, String sub) {
    return (main.length() - main.replace(sub, "").length()) / sub.length();
}

基本的に、ここで行っているのは、 in のすべてのインスタンスを削除した結果の文字列の長さから の長さを差し引くことです。次にmain、この数を の長さで割り、削除されたの出現回数を決定し、答えを求めます。submainsubsub

したがって、最終的には次のようになります。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.next();
    String word9 = sc.next();
    int occurrences = countOccurrences(word8, word9);
    System.out.println(occurrences);

    sc.close();
}
于 2012-09-07T19:32:06.690 に答える
3

あなたも試すことができます:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.nextLine();
    String word9 = sc.nextLine();
    int index = word8.indexOf(word9);
    sc.close();
    int occurrences = 0;
    while (index != -1) {
        occurrences++;
        word8 = word8.substring(index + 1);
        index = word8.indexOf(word9);
    }
    System.out.println("No of " + word9 + " in the input is : " + occurrences);
}
于 2012-09-07T19:35:53.003 に答える
1

なぜ誰も最も明白で迅速な解決策を投稿しないのですか?

int occurrences(String str, String substr) {
    int occurrences = 0;
    int index = str.indexOf(substr);
    while (index != -1) {
        occurrences++;
        index = str.indexOf(substr, index + 1);
    }
    return occurrences;
}
于 2016-11-27T19:44:25.673 に答える