如何使用charAt()和length()编写是否为子字符串方法 [英] How to use charAt() and length() to write a whether is substring method
本文介绍了如何使用charAt()和length()编写是否为子字符串方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个 boolean
方法 subString()
来判断字符串 s1
是否是 s2
.
I want to write a boolean
method subString()
to judge if string s1
is the substring of s2
.
要求仅使用 charAt()
和 length()
以下方法/strong> 字符串
.
例如
Substring("abc","abcd")-> true
Substring("at","cat")->true
Substring("ac","abcd")->false
indexOf()
无法使用.
这是我到目前为止所得到的.
Here is what I got so far.
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.
It fails subString("ac","abcd")
as it returns true.
推荐答案
如果第一个字符匹配,您的代码将返回true.您需要将第一个String的所有字符包含在第二个String的子字符串中.
Your code returns true if the first character matches. You need all the characters of the first String to be contained in a substring of the second String.
我的原始代码有误.这是正确的代码:
My original code was wrong. Here's the correct code :
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;
}
这篇关于如何使用charAt()和length()编写是否为子字符串方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文