2017-04-09 56 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