我需要输入两个字符串,第一个是任何单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:String 1 = CATSATONTHEMAT String 2 = AT。输出将为 3,因为 AT 在 CATSATONTHEMAT 中出现了三次。这是我的代码:
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
。
最佳答案
有趣的解决方案:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
基本上我们在这里做的是减去 main
的长度来自删除 sub
的所有实例所产生的字符串的长度在main
- 然后我们将这个数字除以 sub
的长度确定 sub
的出现次数被删除,给了我们答案。
所以最后你会得到这样的东西:
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();
}
关于java - 获取一个字符串在另一个字符串中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12324249/