我正在编写一个程序,其中包含许多用于赋值的方法,并且在其中一个方法中,我需要找到字符c以字符串s开头的索引。例如:查找索引,其中char c以字符串s开始
IN: sheep, h
OUT: 1
我这样做的方法,但有两个字符串,而不是一个字符串和一个字符
public static int findInStr1(String s1, String s2) {
for (int i = 0; i < s1.length() - s2.length(); i++) {
boolean found = true;
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i) != s2.charAt(j)) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
我试着走动一些事情,使之与一个char工作的,而不是第二个字符串
public static int findInStr2(String s1, char c) {
for (int i = 0; i < s1.length() - 1; i++) {
boolean found = true;
if (s1.charAt(i) != c) {
found = false;
break;
}
if (found) {
return i;
}
}
return -1;
}
,但它总是返回-1无论输入
ŧ提前
为什么你'break'呢?只是摆脱它。 – wns349 2014-11-03 09:04:02
删除'break',你的代码应该可以工作。 – Jens 2014-11-03 09:04:49
为什么不使用[String.indexOf()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)) ? – 2014-11-03 09:04:56