gpt4 book ai didi

java - 计算字符串在字符串中出现的次数

转载 作者:行者123 更新时间:2023-12-02 02:29:19 26 4
gpt4 key购买 nike

这是我对这种方法的尝试。

Count the number of co-occurrances of a non-empty sub-string sub within the string str E.g.

numOccurances("dogmonkeydog","dog") will return 2

numOccurances("dogmonkeydog","mon") will return 1

numOccurances("dogmonkeydog","cow") will return 0

public static int numOccurrences(String str, String sub) {
int result = 0;
int pos = str.indexOf(sub);
if (pos == -1){
return result;
}
if (sub.length() > str.length()){
return result;
}
if ((str.substring(0, sub.length())).equals(sub)){
result++;
String st = str.substring(pos);
return result + numOccurrences(st, sub); //Line 87
}
else{
String st = str.substring(sub.length());
return result + numOccurrences(st, sub);
}
}

对于结果 > 0 的所有测试,我都会遇到此失败

java.lang.StackOverflowError
at java.lang.String.indexOf(String.java:1718)
at java.lang.String.indexOf(String.java:1698)
at eecs2030.lab6.RecursiveTasks.numOccurrences(RecursiveTasks.java:77)
at eecs2030.lab6.RecursiveTasks.numOccurrences(RecursiveTasks.java:87)

我不确定为什么我的代码从未达到其基本情况,任何见解将不胜感激!

最佳答案

您的方法中不需要第三个 if 条件。

 if ((str.substring(0, sub.length())).equals(sub))

您可以简单地将第三种情况定义为

 if(pos>=0)
{
result++;
String newstr = str.substring(pos + sub.length());
return numOccurrences(newstr,sub);
}

因为,如果找到子字符串,pos 变量将通过子字符串的起始索引进行初始化,您可以在此处增加结果。

然后对字符串的其余部分递归调用 numOccurences() 方法。并在方法外部声明变量 result。

 import java.util.Scanner;
class SubString
{
String user,subUser;
Scanner sc=new Scanner(System.in);
int num;
static int result = 0;
int numOccurrences(String str, String sub) {

int pos = str.indexOf(sub);
if (pos == -1){
return result;
}
if (sub.length() > str.length()){
return result;
}
else if(pos >= 0)
{
result++;
String newstr = str.substring(pos + sub.length());
return numOccurrences(newstr,sub);
}
return result;

}

//constructor
SubString()
{
try{
System.out.println("Enter string :");
user=sc.nextLine();
System.out.println("Enter the substring: ");
subUser=sc.nextLine();
num = numOccurrences(user,subUser);
System.out.println(num);
}
catch(Exception e)
{
System.out.println(e);
}

}
public static void main(String...a)
{
new SubString();
}
}

`

关于java - 计算字符串在字符串中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47406012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com