简体   繁体   English

Java使用嵌套循环在另一个字符串中查找一个字符串出现的次数

[英]Java Finding number of occurrences of a string in another string using nested loops

So I'm new to programming. 所以我是编程新手。 I'm using java. 我正在使用Java。 Right now I have an assignment I can't solve on a website that teaches java. 现在,我有一个无法在教授Java的网站上解决的作业。

This is the assignment 这是作业

Write a program that returns number of occurrences of a string in another string. 编写一个程序,该程序返回一个字符串在另一个字符串中出现的次数。

Eg 例如

Input: 输入:

First String: the 第一个字符串:

Second String: The children are playing with their toys because they love it. 第二串:孩子们因为喜欢玩具而在玩玩具。

Output: 输出:

3 3

Note: You should only use nested loops. 注意:您只能使用嵌套循环。 Don't use methods like indexOf or substring. 不要使用indexOf或substring之类的方法。

public static void main(String[] args) {

Scanner input = new Scanner (System.in);
String a = input.nextLine();
String b = input.nextLine();
String z[]  = b.split(" ");
int number=0;
for (int i =0; i<z.length; i++){

if (z[i].contains(a))number++;  


}
System.out.println(number);

I won't give you too much code, but here are the main talking points: 我不会给您太多代码,但以下是主要要点:

  • You need a way to read the input in. This can be accomplished with a Scanner - it's either from STDIN or a file. 您需要一种读入输入的方法。这可以使用Scanner完成-它可以来自STDIN或文件。
  • You need a way to break up each word in the sentence. 您需要一种分解句子中每个单词的方法。 String#split will help you with that. String#split可以帮助您。
  • You need a way to ignore the casing of each sentence - toLowerCase() works well here. 您需要一种忽略每个句子大小写的方法toLowerCase()在这里效果很好。
  • You need to loop over each word in one sentence, as well as each occurrence in the other sentence. 您需要遍历一个句子中的每个单词,以及另一个句子中的每个出现单词。 Consider that String.split produces a String[] , and you can iterate over that with any standard for loop. 考虑到String.split产生一个String[] ,您可以使用任何标准的for循环对其进行迭代。
  • You need a way to see is a string is contained in another string. 您需要一种方法来查看一个字符串是否包含在另一个字符串中。 String#contains will help - although you want to be very careful on which side you're asking contains a string. String#contains会有所帮助-尽管您要非常小心在询问哪一侧包含字符串。 For example: 例如:

     // This will print true System.out.println("The world".toLowerCase().contains("the")); // This will print false System.out.println("the".contains("The world".toLowerCase())); 

Try this : 尝试这个 :

import java.util.Scanner;

public class Occurence {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String str1 = input.nextLine();
        String str2 = input.nextLine();
        int count = 0;
        String word[] = str1.split(" ");

        for (int i = 0; i < word.length; i++) {

            if (word[i].toLowerCase().contains(str2.toLowerCase())) {
                count++;
            }
        }
        System.out.println("Occurence = " + count);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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