从没有库的字符串中查找子字符串。我知道它很简单,但是我无法找到我在哪里被if语句所震惊

时间:2015-04-01 23:06:03

标签: java string

package stringoperation;

import java.util.Scanner;

public class Stringops {
    public static void main(String [] args)
    {
        String string ;
        String sub ; 
        Scanner in = new Scanner(System.in);

        System.out.println("enter a string");
        string =in.nextLine();
        System.out.println("enter a substring to identify");
        sub = in.nextLine();

        char[] array= string.toCharArray(); // converting string to array of char
        char[] subarray  = sub.toCharArray();  //converting sub string to array of char 
        int count=0;
        for(int  j=0;j<array.length;j++)
        {
            if(array[j]==subarray[count]) //till both are same it will run
            {
                if(count==sub.length()-1) //if substring size is reached thats mean matched break out
                {
                    System.out.println("substring is present");
                    break;
                }

                j++;                     
            }

            if(array[j]!=subarray[count]) // otherwise make count as 0 to proceed again 
            {
                count=0;
            }
        }     
    }
}

我检查的if语句仍无法找到错误。我错过了什么。告诉我我做错了什么。

1 个答案:

答案 0 :(得分:0)

在您确定输入字符串采用您期望的格式后,尝试使用string.indexOf(sub) != -1;即控制字符(如换行符)不会附加到输入数据中。有必要记住,如果您要比较的字符串完全匹配,则比较将失败,即

"example" != "Example".