danksim
danksim

Reputation: 627

Java: Contains() method

Trying to implement contains() method without using built-in method contains().

Here is my code:

public static boolean containsCS(String str, CharSequence cs) {
    //char[] chs = str.toCharArray();
    boolean result = false;

    int i=0;
    while(i<str.length()) {
        int j=0;
        while(j<cs.length()) {
            if(NEED TO CHECK IF THERE IS AN INDEX OUT OF BOUNDS EXCEPTION) {
                result = false;
                break;
            }
            if(str.charAt(i+j)==cs.charAt(j)) {
                result|=true; //result = false or true ->>>>> which is true.
                j++;
            } else {
                result = false;
                break;
            }
        }
        i++;
    }
    return false;
}

Let's say:

String   str = "llpll"
Charsequence cs = "llo"

I want to make sure this method works properly in the above case where the Charsequence has one or more char to check but the String runs out length. How should I write the first if statement?

Upvotes: 0

Views: 1292

Answers (5)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Well if it were me first thing I'd check is that the length of my char sequence was <= to the length of my string.

As soon as you chop that logic path out. If the lengths are equal you can just use == Then it would occur that if you chopped up str into cs length parts, you could do a straight comparison there as well.

e.g str of TonyJ and search for a three character sequence would pile through

Ton ony nyJ

One loop, one if statement and a heck of a lot clearer.

Upvotes: 2

Fiery Phoenix
Fiery Phoenix

Reputation: 1166

I'm sure you already know this, but it is in fact possible to see the actual source code of the built-in classes and methods. So I'd take a look there for a start. The String class is especially interesting, IMO.

Upvotes: 0

James
James

Reputation: 1571

If this is for your homework, which I suspect it is, then I suggest you take a look at the API for the String class to see what other methods are available to help find the location of one String within another.

Also consider looking at the source code for String to see how it implements it.

Upvotes: 0

Mike
Mike

Reputation: 473

I would suggest using this and using the contains method therein.

Edit - For the reading impaired: The linked method is not from java.lang.String or java.lang.Object

If you'd bother to actually look at the links, you would see that it is the Apache Commons-Lang API and the StringUtils.contains(...) method that I reference, which very clearly answers the question.

Upvotes: 1

Evans
Evans

Reputation: 1599

if (i+cs.length() > str.length()){
   OUT OF BOUNDS
}

Upvotes: 3

Related Questions