本文介绍了获取另一个字符串中一个字符串的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要输入两个字符串,第一个是任何单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:String 1 = CATSATONTHEMAT String 2 = AT。输出为3,因为AT在CATSATONTHEMAT中出现三次。这是我的代码:
I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
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
当我使用这段代码时。
It outputs 1
when I use this code.
推荐答案
您也可以尝试:
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);
}
这篇关于获取另一个字符串中一个字符串的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!