这是我写的实现LastIndexOf 方法的功能public class LastIndexOf
{
public static void main(String[] args)
{
String srcText = "cx8923ulfk;dji-abc321fckdu9a-832abc-894ofjdksau9-83791piufdsiaabcfodsa";
String str = "abc";
int hits = 0;
int idx = 0 ;
for(  int i = 0; i < srcText.length(); i ++)
{
if(srcText.charAt(i) == str.charAt(hits))
{
hits += 1;
    if( hits == str.length())
    {     
     idx = i - str.length() + 1;     
     hits = 0;
    }
}
else
     hits = 0;


System.out.println(idx);
System.out.println(srcText.lastIndexOf("abc"));
}
} idx是我定义的最后一次出现的位置,可是循环执行到倒数第二次就完了,问题出在哪了呢?

解决方案 »

  1.   

    cx8923ulfk;dji-abc321fckdu9a-832abc-894ofjdksau9-83791piufdsiaabcfodsa你把最后一个abc前面的a去掉就知道是什么原因了。
      

  2.   

    在你的基础上帮你做了小修改,你自己想想和你之前的做法有什么区别吧
    public class LastIndexOf
    {
    public static void main(String[] args)
    {
    String srcText = "cx8923ulfk;dji-abc321fckdu9a-832abc-894ofjdksau9-83791piufdsiaabcfodsa"; 
    String str = "abc";
    int hits = 0;
    int idx = 0 ; 
    for( int i = 0; i < srcText.length(); i ++)
    {
    if(srcText.charAt(i) == str.charAt(0))
    { //第一个字符相同
        boolean match = false;
        for (int j=1; j<str.length() && i+j<srcText.length(); j++) { //继续比较后续字符
            if (srcText.charAt(i+j) != str.charAt(j)) {break;}
            match = (j==str.length()-1); //后续字符全部一致
        }
        if (match) {idx=i;} //则获取该位置
    }} 
    System.out.println(idx); 
    System.out.println(srcText.lastIndexOf("abc"));

    }