简体   繁体   中英

Java - String.lastIndexOf(str) logic I cannot understand

I used two different string to test the last index of "\\t", but they both return 4. I thought it should be 5 and 4. I checked the oracle docs and I could not understand why. Could someone please tell me why? Thank you!

System.out.println("abc\t\tsubdir".lastIndexOf("\t"));
System.out.println("abct\tsubdir".lastIndexOf("\t"));

Lets make the number of indexes to understand it better :

String 1

a b c \t \t s u b d i r
0 1 2  3  4 5 6 7 8 9 10
          ^-----------------------------------last index of \t (for that you get 4)

String 2

a b c t \t s u b d i r
0 1 2 3  4 5 6 7 8 9 10
         ^-----------------------------------last index of \t (for that you get 4)

There are some special characters that should be escaped by \\ (tab \\t , breadline \\n , quote \\" ...) In Java, so it count as one character and not 2

In the first line, the last tab is at 4 abc <tab> <tab>

In the second line, the last tab is at 4 also abct <tab>

\\t counts as 1 character

This is because the \\t does not count as two characters, it is an escape sequence and counts for only one character.

You can find the full list of escape sequences here : https://docs.oracle.com/javase/tutorial/java/data/characters.html

It's important to note that the count starts from zero and '\\t' only counts as one character. This can be confusing at times especially if you forget to start form zero.

0|1|2| 3| 4
a|b|c|\t|\t
a|b|c| t|\t

The count start with zero in java, that the reason why first and sysout returns 4. for your better understanding i added 3rd sysout where you can find the last index of \\t will returns zero.

/**
 * @author itsection
 */
public class LastIndexOf {
    public static void main(String[] args) {
        System.out.println("abc\t\tsubdir".lastIndexOf("\t"));
        System.out.println("abct\tsubdir".lastIndexOf("\t"));
        System.out.println("\tabctsubdir".lastIndexOf("\t"));
    }
}// the output will be 4,4,0

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