用户定义的String函数?

时间:2015-02-21 03:15:31

标签: java string user-defined-functions

我在Java中有以下代码:

 public class StringSearch
{
 public static void main(String[] args)
  {

    String s = new String("I love my school. I love to play basketball. It is lovely weather. Love is life.");
    System.out.println(s);
    int i = -1;
    int count = 0;
    System.out.print("Counting love:");
    do{
      i = s.findW("love");
      if(i != -1){
        count++;
        System.out.print(count+" ");
      }
    }while(i != -1);
    System.out.println("The word \"love\" appears "+count+" times.");
  } 
}

我知道s.findW()是不正确的,因为没有为Class String定义findW()。但是,是否可以在类String中添加用户定义的函数并修复此问题?

修复此问题的其他选择吗?

提示此问题是阅读JDK文档并修复代码。 :/

3 个答案:

答案 0 :(得分:0)

Java String类是final,不能更改。你可以写自己的,但那会很疯狂。 String上通常有足够的功能。如果它不能达到你想要的效果,可以用一些方法编写一个辅助类。

答案 1 :(得分:0)

我会使用indexOf方法,如下所示:

    String s = new String("I love my school. I love to play basketball. It is lovely weather. Love is life.").toLowerCase();
    System.out.println(s);
    int i = 0;
    int count = 0;
    System.out.print("Counting love:");
    while(i != -1)
    {
      i = s.indexOf("love");
      if(i != -1){
        count++;
        s = s.substring(i+1);
        System.out.print(count+" ");
      }
    }
    System.out.println("The word \"love\" appears "+count+" times.");

根据您是否希望答案为3或4,您需要在其中使用toLowerCase,以便Love匹配或不匹配。

答案 2 :(得分:0)

Java正则表达式是你的朋友!

String s = "I love my school. I love to play basketball. It is lovely weather. Love is life.".toLowerCase();
     int count = (s.length() - s.replaceAll("love", "").length()) / 4;
     System.out.println("The word \"love\" appears " + count + " times.");