2014-11-03 53 views
0

我正在编写一个程序,其中包含许多用于赋值的方法,并且在其中一个方法中,我需要找到字符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无论输入

ŧ提前

+0

为什么你'break'呢?只是摆脱它。 – wns349 2014-11-03 09:04:02

+0

删除'break',你的代码应该可以工作。 – Jens 2014-11-03 09:04:49

+1

为什么不使用[String.indexOf()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)) ? – 2014-11-03 09:04:56

回答

3

这一行:

if (s1.charAt(i) != c) { 

它是做什么的?它看起来看这个角色是不是你要找的目标。所以在大多数情况下,这会触发第一个字符。

接下来,您有一个break语句之前,你有你的return语句。请记住,break只是循环,而不是if语句。如果你找到它,不要使用找到的变量。只需返回索引就可以了。

if (s1.charAt(i) == c) { 
    return i; 
} 

最后,你有这个作为你的条件:

for (int i = 0; i < s1.length() - 1; i++) 

你必须选择一个或其他。请使用<= s1.length() - 1或使用< s1.length()。如果你俩都这样做,你会错过最后一个角色。所以"sheep", 'p'回报没有发现时,它应该返回4.

1

汉克斯当它没有发现你身边的首次设立发现虚假和break,注意:break,跳出整个循环的不if语句,因此返回-1

尝试写更紧凑,更简单的代码,下面的代码不正是你想要的,

import java.util.*; 

public class Found{ 

public static int findInStr2(String s1, char c) { 
    for (int i = 0; i < s1.length(); i++) 
    { 
     if (s1.charAt(i)==c) 
     { 
     return i; 
     } 

    } 
return -1; 
} 
public static void main(String[] args) 
{ 

Found f=new Found(); 
int pos=Found.findInStr2("Hello",'o'); 
System.out.println("found at position"+(pos+1)); 
}//main ends 

}//class ends 
1

我不认为你需要断言。这很早就让你摆脱了for循环。

您应该能够通过在boolean found声明之前添加一个system.out.println来证明这一点,以追踪您的索引是什么。

1

试试这个

for (int i = 0; i < s1.length() - 1; i++) { 
    if (s1.charAt(i) == c) { 
     return i; 
    } 
} 
return -1;