字符串的用户定义函数?

User defined function for String?

我在 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 字符串定义 findW()。但是,是否可以在 class 字符串中添加用户定义的函数并修复此问题?

有什么替代方法可以解决这个问题?

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

Java 字符串 class 是最终的,无法更改。你可以自己写,但那太疯狂了。通常 String 上已经有足够的功能。如果它不能满足您的要求,请使用一些方法编写一个帮助程序 class。

我将按如下方式使用 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 匹配或不匹配。

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.");