拆分和比较一个字符串(Java)
我已经测试了一段时间不同的方法,这就是我得到的。我就是想不出怎么解决这个问题拆分和比较一个字符串(Java),java,string,Java,String,我已经测试了一段时间不同的方法,这就是我得到的。我就是想不出怎么解决这个问题 /** Return true iff s has an odd number of characters and * the substring before the middle character equals the substring * after it. * Examples: For s = "" return false * For s = "b" return true * For s
/** Return true iff s has an odd number of characters and
* the substring before the middle character equals the substring
* after it.
* Examples: For s = "" return false
* For s = "b" return true
* For s = "xbx" return true
* For s = "xxxx" return false
* For s = "hellohello" return false
* For s = "hello!hello" return true */
public static boolean isDoubled(String s) {
// TODO 1. There is no need for a loop. Do not use a loop.
// In all methods, use s1.equals(s2) and NOT s1 == s2 to test
// equality of s1 and s2.
int midLen = s.length() / 2;
if (midLen == 0) return false;
String[] parts = {s.substring(0, midLen - 1), s.substring(midLen + 1)};
String part1 = parts[0];
String part2 = parts[1];
if ((s.length() % 2 == 0) && (part1.equals(part2))) {
return true;
}
return false;
}
使用
子字符串
函数时出错:
public static boolean isDoubled(String s) {
if (s.length() % 2 == 0)
return false;
if (s.length() == 1)
return true;
int mid = s.length() / 2;
return s.substring(0, mid).equals(s.substring(mid + 1));
}
两个简单的错误:
- 在
如果要确定长度是否为偶数,则需要确定长度是否为偶数。(将if语句中
更改为(s.length()%2==0)
!(s.length()%2==0)
- 而且
函数不包括在内,因此您希望将substring
更改为s.substring(0,mid-1)
(来自:“子字符串从指定的beginIndex开始,并延伸到索引endIndex-1处的字符。”)s.substring(0,mid)
数组的两部分放入变量中。您只需将它们进行如下比较:
<代码>部分[0 ] .=(部分[1)] < /代码> 当您将两个索引(a,b)传递到子串方法时,该方法包括索引和排除索引b。数学上,它是[a,b)。如果您考虑字符串“Hello,Hello”,MID将是索引5。
String[] parts = {s.substring(0, midLen - 1), s.substring(midLen + 1)};
你得到的两个部分是
s.substring(0, 4) //this gets you the string "hell"
s.substring(6) //this gets you the string "hello"
显然,它们不匹配。导致错误的等价
你需要的是一点零钱-
String[] parts = {s.substring(0, midLen), s.substring(midLen + 1)};
你的代码有什么问题?