Carl
Carl

Reputation: 107

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"));

Upvotes: 3

Views: 424

Answers (5)

Konzern
Konzern

Reputation: 128

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

Upvotes: 0

Steven Spungin
Steven Spungin

Reputation: 29099

In the first line, the last tab is at 4 a b c <tab> <tab>

In the second line, the last tab is at 4 also a b c t <tab>

\t counts as 1 character

Upvotes: 4

John Ciociola
John Ciociola

Reputation: 97

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

Upvotes: 2

Emmanuel H
Emmanuel H

Reputation: 92

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

Upvotes: 3

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

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

Upvotes: 10

Related Questions