【问题标题】:Lastindexof() isn't workingLastindexof() 不起作用
【发布时间】:2016-08-15 20:34:53
【问题描述】:

例如,我在文本文件中有 2 行数据: 你好!早晨 你好!晚上

我只想要一行的最后一个字。我使用了这段代码,但不是显示 Evening,而是显示 Hi!晚上 searchName 是嗨!

try{
            BufferedReader in = new BufferedReader(fr);

            try {
                while((s=in.readLine())!=null){
                    countline++;
                    String[] words=s.split(" ");


                    for(String word:words){
                        if(word.contains(searchName)){
                            System.out.println(words);
                            int lastSpace=word.lastIndexOf(" ");
                            String addres=word.substring(lastSpace+1,word.length());

                            System.out.println(addres);

                        }
                    }
                }
                in.close();

            } catch (IOException e) {
                System.out.println("No address found for your name..We are updating");
            }
        }finally {

        }

【问题讨论】:

    标签: java substring


    【解决方案1】:

    看起来像家庭作业问题。所以不会给出确切的答案。

    以下代码应该向您解释如何正确使用 split() 并获取所有值:

    String in = "Hello! Morning Hi! Evening";
    
    String[] words = in.split(" ");
    
    for (int i = 0; i < words.length; i++) {
    
        if(words[i].equals(yourSearchString)){
          System.out.println("Your Search String" + words[i]);
        }
    }
    // to get the last word
     String lastWord = words[words.length - 1];
    

    【讨论】:

    • 我很困惑为什么我的词没有用空格分割。后来我注意到,我在这些词之间使用了制表符。int lastSpace=word.lastIndexOf("\t");这有效
    【解决方案2】:

    您可能需要阅读 split() 的 API。 http://www.tutorialspoint.com/java/java_string_split.htm

    如果你想要一行的最后一个单词,你已经得到了。它会在

    words[words.length - 1].
    

    如果您仍想使用lastIndexOf(),您可以,但不要使用split(),然后在这些元素上循环,您只需要

    String addres = word.substring(word.lastIndexOf(" ") + 1);
    

    但你不能两者都做。目前,您正在删除String 中的所有空格,方法是使用split() 将其切碎,然后在切碎的String 的每个部分中查找空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 2020-07-21
      • 1970-01-01
      • 2018-07-03
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      相关资源
      最近更新 更多