简体   繁体   English

Java-我无法理解的String.lastIndexOf(str)逻辑

[英]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. 我使用了两个不同的字符串来测试“ \\ t”的最后一个索引,但是它们都返回4。我认为应该是5和4。我检查了oracle文档,但我不明白为什么。 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 弦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 弦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 \\中应该转义一些特殊字符(制表符\\t ,面包线\\n ,引用\\" ...),因此在Java中,它算作一个字符而不是2

In the first line, the last tab is at 4 abc <tab> <tab> 在第一行中,最后一个标签页位于4 abc <tab> <tab>

In the second line, the last tab is at 4 also abct <tab> 在第二行中,最后一个选项卡也在4处abct <tab>

\\t counts as 1 character \\t算作1个字符

This is because the \\t does not count as two characters, it is an escape sequence and counts for only one character. 这是因为\\t不会算作两个字符,而是一个转义序列,只算一个字符。

You can find the full list of escape sequences here : https://docs.oracle.com/javase/tutorial/java/data/characters.html 您可以在此处找到转义序列的完整列表: 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. 重要的是要注意,计数从零开始,“ \\ t”仅计为一个字符。 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. 在Java中,计数从零开始,这就是first和sysout返回4的原因。为了更好地理解,我添加了第3 sysout,在其中可以找到\\ t的最后一个索引将返回零。

/**
 * @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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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