find substring

package algorithm.weixin;

public class FindSubString {
    /***
     * str HelloWorld
     * substr world
     *
     *
     * @param str
     * @param substr
     * @return
     */
    public static int findSubstr( String str, String substr )
    {
        if( str == null || substr == null )
        {
            return -1;
        }
        if( str.trim().length() == 0 )
        {
            return -1;
        }
        int i = 0, j = 0;
        for( ; i < str.length(); i++ )
        {
            j = 0;
            if( str.charAt( i ) == substr.charAt(0) )
            {
                int initPos = i;
                int counter = 0;
                while( j+1 < substr.length() && str.charAt( ++initPos ) == substr.charAt( ++j )  )
                {
                    counter++;
                }
                if( counter == substr.length() - 1 )
                {
                    return i;
                }
                else
                {
                    continue;
                }
            }
        }
        return -1;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        int i = findSubstr( "hellowold", "world" );
        System.out.println( i );

    }

}

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s