【问题标题】:JAVA: method, how many occurrences of a string appear in another string [duplicate]JAVA:方法,一个字符串在另一个字符串中出现了多少次[重复]
【发布时间】:2017-04-28 14:37:55
【问题描述】:

我是学习 java 编程的新手,在这里我被困在这个作业上。我无法弄清楚我在代码中做错了什么,所以我可以得到具体的结果。有关如何解决问题的任何帮助或提示都会有所帮助。提前致谢。

这个赋值将编写一个方法来确定一个字符串在另一个字符串中出现的次数。

具体来说,你应该做到以下几点:

  1. 在 StringsSecondAssignments 项目中创建一个名为 Part2 的新 Java 类。

  2. 编写名为 howMany 的方法,该方法有两个字符串参数,名为 stringa 和 stringb。此方法返回一个整数,指示 stringa 在 stringb 中出现的次数,其中 stringa 的每次出现不得与它的另一次出现重叠。例如,调用 howMany(“GAA”, “ATGAACGAATTGAATC”) 返回 3,因为 GAA 发生了 3 次。调用 howMany(“AA”, “ATAAAA”) 返回 2。注意找到的 AA 不能重叠。

  3. 编写无参数的void方法testHowMany。在此处添加代码以使用几个示例调用 howMany 并打印结果。仔细考虑哪些类型的示例适合进行测试,以确保您的方法正常工作。

这是我的代码:

public class Part2in {

   public String HowMany(String stringa, String stringb) {
   int lastIndex = 0;
   int count = 0;
   while (lastIndex != -1){
       lastIndex =stringb.indexOf(stringa, lastIndex);
       if(lastIndex !=-1){
           count = count + 1;
           lastIndex = stringa.length();
        }

       System.out.println(count);
    }

    return "";    

}
public void testHowMany() {

   String stringB = "ABCDASDFBCSDSDFBCBDSDBC";
   String stringA = "BC";
   String counts = HowMany(stringB, stringA);
   if (counts.isEmpty()) {
       System.out.print("ERROR" );
    }
   else {
       System.out.print("CORECT" + counts);
    }
  }
}

【问题讨论】:

  • 提示:您将 lastIndex 设置为 String a 的长度。我认为您想将其增加字符串 a 的长度。

标签: java


【解决方案1】:

一个简单的while 就可以完成这项工作:

@Test
public void testIt(){
    String a = "abcdesdikdikcdkofkvcdqwppqcddddcdlpqa";
    String b = "cd";

    int i = 0;
    while (a.contains(b)){
        a = a.replaceFirst(b,"");
        i++;
    }
    System.out.println("found:"+i);

}

在我的情况下打印你5

【讨论】:

    【解决方案2】:

    你可以在一行中做到这一点:

    System.out.println("ATAAAA".split("AA", -1).length - 1);
    

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 2013-02-11
      • 2021-12-25
      • 1970-01-01
      • 2014-03-04
      • 2014-06-13
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多