我需要输入两个字符串,第一个字符串是任何单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:字符串 1 = CATSATONTHEMAT 字符串 2 = AT。输出将为 3,因为 AT 在 CATSATONTHEMAT 中出现了 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
当我使用这段代码时。
有趣的解决方案:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
基本上我们在这里做的是减去长度main
删除所有实例后得到的字符串长度sub
in 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)