3

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"));
Carl
  • 107
  • 8
  • 5
    Are you confused by the length of `\t`? That's a String literal, its length at runtime will be one, a character representing a tab. See https://stackoverflow.com/questions/34393312/get-actual-length-of-the-defined-string-in-java – Sotirios Delimanolis Aug 23 '18 at 19:58

5 Answers5

10

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

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
4

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

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
3

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

Emmanuel H
  • 82
  • 8
2

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
0

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
Konzern
  • 110
  • 10