我想写一个boolean
方法subString()
来判断字符串s1
是否是s2
的子串>.
要求只是使用 charAt()
和 length()
方法 字符串
。
例如
Substring("abc","abcd")-> true
Substring("at","cat")->true
Substring("ac","abcd")->false
indexOf()
不能使用。
这是我到目前为止得到的结果。
public class Q3 {
public boolean subString(String str1, String str2) {
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
for (i = 0; i < s1.length; i++) {
for (j = 0; j < s2.length; j++) {
if (s1.charAt(i) == s2.charAt(j))
return true;
}
}
return false;
}
}
测试类是:
public class Q3test {
public static void main (String arg[]){
Q3 Q3object = new Q3();
System.out.println(Q3object.Substring("ac","abcd"));
}
}
subString("ac","abcd")
失败,因为它返回 true。
最佳答案
如果第一个字符匹配,您的代码将返回 true。您需要第一个字符串的所有字符都包含在第二个字符串的子字符串中。
编辑:
我的原始代码是错误的。这是正确的代码:
public static boolean subString(String str1, String str2)
{
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
for (int offset = 0; offset <= s2.length() - s1.length(); offset++) {
int i = 0;
for (; i < s1.length(); i++){
if(s1.charAt(i) != s2.charAt(i+offset)) {
break;
}
}
// found a substring that starts at the current offset
if (i == s1.length())
return true;
}
return false;
}
关于java - 如何用charAt()和length()写一个是否为子串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827309/