简体   繁体   English

用该行末尾的单词替换文本文档中的整行

[英]Replace the whole line in the text document with the word at the end of the line

I am trying to replace the line with the word at the end of the line. 我试图用该行末尾的单词替换该行。 Standing with the current I am getting the same line. 站在当前,我得到的是同一行。

Simple: 简单:

apple - water- wall - street- light- book

REsult should be 结果应该是

book

Code: 码:

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.contains("-") ) {                   
        String[] lineSplitted = line.split("-");
        int index = lineSplitted.length - 1;
        String direction = lineSplitted[index];
        line.replace(line, direction);
    }   
}

如果您要完成的工作是将输入行替换为该行的最后一个单词,则只需将代码更改为以下内容:

Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); String[] parts = line.split("\\\\s"); line = parts[parts.length-1];

The type String is immutable, meaning that once constructed, the object itself cannot be changed. String类型是不可变的,这意味着对象一旦构造,就无法更改。 Instead of trying to update the string itself, update the reference ( line=direction; ). 而不是尝试更新字符串本身,而是更新引用( line=direction; )。

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

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