【问题标题】:User defined function for String?字符串的用户定义函数?
【发布时间】:2015-04-22 21:09:46
【问题描述】:

我在 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() 是不正确的,因为 findW() 没有为 Class String 定义。但是,是否可以在 String 类中添加用户定义的函数并修复此问题?

有什么办法可以解决这个问题吗?

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

【问题讨论】:

  • “是否可以在类 String 中添加用户定义的函数”String 类是 final,如文档中所述。您可以将此方法添加到其他类型,或使用其他方法,如 containsindexOf(文档中也提到)
  • “这个问题的提示是阅读 JDK 文档并修复代码。” 那么这是一个测验吗?
  • 创建自己的findW(String string) 方法并使用它?这是什么?
  • 参见 String.indexOf...

标签: java string user-defined-functions


【解决方案1】:

我会使用 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 匹配或不匹配。

【讨论】:

  • 谢谢!真的很尴尬,我没有意识到 String 类是 final 的。感谢您的帮助!
  • 一个快速的问题。使用它,程序也将“可爱”标识为找到的字符串。我怎样才能排除这个?
  • 在创建新字符串时去掉 toLowerCase()。我不确定你是否想加入 Lovely。
  • 嗯.. 我的意思是即使是“可爱”,或者说,“真爱”也会被识别为找到。再举一个例子——“loveman”或“like-love”。很抱歉再次打扰您。
  • 如果你说你只想要完整的单词 love 然后执行以下操作: String[] str = s.split[" "]; for(int i = 0; i
【解决方案2】:

Java String 类是最终的,不能更改。你可以自己写,但这太疯狂了。 String 上通常已经有足够的功能性了。如果它不符合您的要求,请编写一个带有一些方法的辅助类。

【讨论】:

  • 谢谢!!它有帮助。 :)
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多