简体   繁体   English

涉及字符串的Java程序输出的问题

[英]Issue with output of java program involving string

class Blue_ManTest{

    public static void main(String[] args){
        String name = "I LOVE JAVAWORLD";
        int index1 = name.indexOf(" ");
        int index2 = name.lastIndexOf(" ");
        String str1 = name.substring(0, index1);
        String str2 = name.substring(index1 + 1, index1+ 5);
        String str3 = name.substring(index2 + 5);
        System.out.println(str3 + ", " + str1 + " " + str2 + ".");
    }
}   

I am having trouble figuring out what would be the output of this program I think I know it but I am not sure. 我想弄清楚该程序的输出是什么,我想我知道,但是不确定。

I did this I Love JavaWorld with 0 corresponding to j and 15 to D with 1 being the space between. 我这样做是因为我爱JavaWorld,其中0对应于j,15对应于D,其中1是空格。

for str1 I get I 对于str1我得到I

for str2 I get Love 对于str2我得到Love

but for str3 I get avaWorld 但是对于str3我得到avaWorld

But str3 seems wrong to me as it would print out. 但是str3对我来说似乎是错误的,因为它将打印出来。

avaWorld, I  Love.    

Your str3 variable is taking a substring that starts at index2 + 5 where index2 is the index of the last space in your input string: 您的str3变量采用以index2 + 5开头的子字符串,其中index2是输入字符串中最后一个空格的索引:

int index2 = name.lastIndexOf(" ");

That is, index2 is 6. And of course 6 + 5 is 11. 也就是说, index2是6。当然6 + 5是11。

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

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