Java 获取一个字符串在另一个字符串中的出现次数
我需要输入两个字符串,第一个字符串是任意单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:String 1=catsatonhemat String 2=AT。输出将为3,因为AT在CATSATONHEMAT中出现三次。这是我的密码:Java 获取一个字符串在另一个字符串中的出现次数,java,string,indexof,Java,String,Indexof,我需要输入两个字符串,第一个字符串是任意单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:String 1=catsatonhemat String 2=AT。输出将为3,因为AT在CATSATONHEMAT中出现三次。这是我的密码: public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word8 = sc.next();
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();
}
您也可以尝试:
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);
}
另一种选择:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
startsWith
和endsWith
是必需的,因为split()
省略了尾随的空字符串。为什么没有人发布最明显、最快速的解决方案
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}
indexOf
不返回计数,它返回第一次出现的位置。精确复制到:@Brian这就是他寻求帮助的原因。不管怎么说,regex起到了解救作用?为什么从来没有人想写一个循环??聪明:),但会更好,因为它不使用像。replaceAll
这样的正则表达式,并且它的语义与您使用它的语义相同。谢谢,这是一种有趣的方法。别忘了关闭扫描仪。