简体   繁体   中英

what does while (n— != 0){} is doing in this code?

in the following code what does this line translates to?

while (n-- != 0){} ? if i am not mistaking n is 18 when length of searchMe is deducted form length of substring, so does this line says while 18 decremented (17) is not equal to 0 do the search?

class ContinueWithLabelDemo {
    public static void main(String[] args) {

        String searchMe = "Look for a substring in me";

        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() - 
                  substring.length();


    test:
        for (int i = 0; i <= max; i++) {

            int n = substring.length();

            int j = i;

            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

The condition n-- != 0 means "Check that n is not equal to zero before decrementing it; set n to n-1 after the check."

This means that when n is equal to some number K before the loop, then the loop would repeat exactly K times.

while (n-- != 0) { // checks  (n != 0) then n = n-1;
     if (searchMe.charAt(j++) != substring.charAt(k++)) {
            continue test;
     }
}

this n-- will do post decrement, first it will check the condition then it will decrease the value of n by 1.

Suppose value of n is 10. then first it will check the condition,
if(10 != 0) and after this it will decrease to 9.

In your code you have written:

 while (n-- != 0) {
       if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
        }
}

So if you replace your code with below code:

    while (n != 0) {
           n = n-1;
           if (searchMe.charAt(j++) != substring.charAt(k++)) {
                            continue test;
           }
    }

These two codes would work exectly same, so I think by comparison you can understand it's meaning.

n-- is actually a method that behind the scenes changes the value of n to n-1, but returns the actual value of n currently because it is a postfix operation in this case.

If it was a prefix operation (--n) then yes the value returned would be 17 first as you said.

Basically, n-- means take the current value of n and use that for this line, but after this current line, decrement the value by one. In this case, the first value of n would be the length of the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM