2015-06-03 96 views
0

我想用文本文檔中-連字符來代替?問題標記,但它被發現,但沒有更換查找字符串和文本文檔中替換

Bad Schwartau ? Stockelsdorf ? ZOB/Hbf. ? Sandstr. ? Universitätsklinikum ? Grillenweg 
9 
Haltestellen Montag ? Freitag 
Bad Schwartau/ZOB ... 04:21 04:54 05:40 06:03 06:18 06:33 06:48 07:03 07:21 07:33 08:03 11:03 

代碼:

try { 
    scanner = new Scanner(file); 

    int lineNum = 0; 
    while (scanner.hasNextLine()) { 
     String line = scanner.nextLine(); 
     lineNum++; 
     if(line.contains("?")) { 
      line.replace("?", "-"); 
      System.out.println("I found it on line " + lineNum); 
     } 
    } 
} 
+4

使用'線= line.replace(, 「 - 」, 「?」);'' – Reimeus

+1

與string.replace()'返回與子字符串的替換的值。它不*改變原始字符串,並且絕對不會改變它從中讀取的文件。您必須用適當的行編寫新文件,然後切換文件。 – RealSkeptic

+0

你忽略了line.replace()的返回值 – swingMan

回答

2

Java String是不可變的 - 這意味着它不能被更改,只能被替換。

嘗試此代替 -

line = line.replace("?", "-"); 
+0

我已經嘗試過但它不起作用 –

+0

堅持 - 你期待什麼?你不打印輸出? –

+0

以及如何打印出來?請你可以編輯你的答案 –