java - How to use charAt() and length() to write a whether is substring method -
i want write boolean
method substring()
judge if string s1
substring of s2
.
the requirement use charat()
and length()
methods of string
.
e.g.
substring("abc","abcd")-> true substring("at","cat")->true substring("ac","abcd")->false
indexof()
cannot used.
here got far.
public class q3 { public boolean substring(string str1, string str2) { string s1 = str1.tolowercase(); string s2 = str2.tolowercase(); (i = 0; < s1.length; i++) { (j = 0; j < s2.length; j++) { if (s1.charat(i) == s2.charat(j)) return true; } } return false; } }
test class :
public class q3test { public static void main (string arg[]){ q3 q3object = new q3(); system.out.println(q3object.substring("ac","abcd")); } }
it fails substring("ac","abcd")
returns true.
your code returns true if first character matches. need characters of first string contained in substring of second string.
edit:
my original code wrong. here's correct code :
public static boolean substring(string str1, string str2) { string s1 = str1.tolowercase(); string s2 = str2.tolowercase(); (int offset = 0; offset <= s2.length() - s1.length(); offset++) { int = 0; (; < s1.length(); i++){ if(s1.charat(i) != s2.charat(i+offset)) { break; } } // found substring starts @ current offset if (i == s1.length()) return true; } return false; }
Comments
Post a Comment