[英]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: 我不会给您太多代码,但以下是主要要点:
Scanner
- it's either from STDIN or a file. Scanner
完成-它可以来自STDIN或文件。 String#split
will help you with that. String#split
可以帮助您。 toLowerCase()
works well here. toLowerCase()
在这里效果很好。 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.