编写一个方法来查找在另一个字符串里的特定字符串。如果字符串存在,则方法必须返回真。例如:isSubString(“cat”, “The cat in the hat.”)是true,而isSubString( “bat”, “The cat in the hat.”)是false。
另外,验证边界条件也要遇到。
 isSubString(“The”, “The cat in the hat,”)是true
 isSubString(“hat.”, “The cat in the hat.”)是true。
提示-可以使用String类的charAt(int index)方法找到某个字符串中的特定字符;index是从0开始。例如:“cat”.charAt(0)是‘c’、 “cat”.charAt(1)是 ‘a’、 “cat”.charAt(2)是 ‘t’。length方法返回字符串中的字符数目:例如:“cat”.length()是3。我写的这个程序很麻烦,而且这个方法我还不怎么会用。
我刚学JAVA,请那位大哥帮忙解决一下!

解决方案 »

  1.   

    boolean isSubString(String a, String b) {
      return b.indexOf(a) != -1;
    }
      

  2.   

    java.lang.String:
    indexOf
    public int indexOf(String str)
    Returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that: 
     this.startsWith(str, k)
     
    is true. Parameters:
    str - any string. 
    Returns:
    if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned. 
    Throws: 
    NullPointerException - if str is null.
      

  3.   

    public class StrCmp {
    boolean isSubString(String a, String b) {
    return b.indexOf(a) != -1;
    }
    public static void main(String[] args) {String a="hat.";
    String b="The cat in the hat.";
    System.out.println(new StrCmp().isSubString(a,b));
    }
    }同意!