2017-04-09 57 views
0

您好那裏的所有編碼字符串中的字符,任何幫助表示讚賞,這是一個個人項目,而不是爲我以爲會很有趣的一所學校,但沒有談到了將所以。現在該項目是讀入一個輸入文件,將其與一個srting []字母= {「a」,「b」,「c」....「z」}進行比較,然後用另一個字符串替換字母[ ] newAlphabets = {「蘋果」,「球」,「貓」,....「斑馬」}。現在我已經嘗試了簡單的replaceAll()示例,它有點工作。但計劃是輸入一個.txt文件,並用新文件進行替換運行並輸出。 JamesBond.txt:姓名是Bond,James Bond。 Output.txt的應該是:NoAppleMonkeyElephant InsectSnake BallOpenNoDuck,JungelAppleMonkeyElephantSnake BallOpenNoDuck。 這是我到目前爲止有:代從Java中的字符串數組

import java.io.IOException; 
import java.io.File; 
import java.util.Scanner; 

public class FnR { 
// array of alphabets 
static String[] alphabet = {"a","b","c","d","e","f","g","h","i", 
     "j","k","l","m","n","o","p","q","r","s","t","u", 
     "v","w","x","y","z"}; 
// replace the alphabets with substituted string 
static String[] newAlphabets = 
{"Apple","Bat","Cat","Dog","Egale","Fox","Goat","Horse","Insect","Jungle", 
"King","Lion","Monkey","Nose","Open","Push","Quit","Run","Stop","Turn", 
"Up","Volume","Water","X-mas","Yes","Zip"}; 
@SuppressWarnings("resource") 
public static void main(String[] arg) throws IOException{ 
    try { 
     //reads in the file 
     Scanner input = new Scanner("JamesBond.txt"); 
     File file = new File(input.nextLine()); 
     input = new Scanner(file); 

     while (input.hasNextLine()) { 
      String line = input.nextLine(); 
      //prints the txt file out 
      System.out.println(line); 
      // replaces the letter j with Jungel in the text regardless of 
     case 
      String newtxt1 = line.replaceAll("J","Jungle"); 

      //prints new text 
      System.out.println(newtxt1); 
     } 
     input.close(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} } 
Output: 
Name is Bond, James Bond 
Name is Bond, Jungleames Bond 
+0

非常抱歉,我的錯誤。 – SurgeJ

回答

1

不會給你的代碼。這個答案提供了一些提示,讓你自己編寫代碼。

請勿使用replaceAll()。你必須做26次,這不是一個很好的解決方案。

相反,建立結果字符串創建StringBuilder。然後使用字符串方法length()charAt()以正常的for循環遍歷輸入字符串的字符。

現在,這裏是簡化代碼的主要「技巧」。 Java以Unicode存儲文本,其中連續存儲字母az。這意味着你可以用計算這個索引到你的newAlphabets數組中。要做到這一點,你會寫這樣的代碼:

char ch = ...; 
if (ch >= 'a' && ch <= 'z') { 
    int idx = ch - 'a'; // number between 0 and 25, inclusive 
    // use idx here 
} else if (ch >= 'A' && ch <= 'Z') { 
    int idx = ch - 'A'; // number between 0 and 25, inclusive 
    // use idx here 
} else { 
    // not a letter 
} 

希望這可以幫助你自己寫代碼。

+0

哎呀!錯字固定。 – Andreas

+0

非常感謝您的幫助安德烈亞斯我會盡力按照您的建議解決問題並回復您。所以,在未來的任何幫助或建議表示讚賞。 – SurgeJ