基本上,我正在编写一个程序,该程序接受一大块文本(如一篇文章),并根据其他两个字符串行替换字符,这两个字符串行被纳入程序中,如下所示:
uvxftkbsqpznlcwdeijhoamgyr
etaoinsrhldcumfpgwybvkxjqz
程序迭代大文本 block 中的字符,如果某个字符与顶行字符匹配,则将其替换为下面的字符。 我已将两个字符串行放入 LinkedHashMap 中以便于访问,但由于某种原因,程序无法正确替换字符。这是我的代码:
public class MyReplacer{
public static void main(String[] args) throws IOException {
String fileName = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter file name");
fileName = in.nextLine();
BufferedReader readerForText = new BufferedReader(new FileReader(fileName));
Scanner keyFileReader = new Scanner(new File("Key.txt"));
String topLine = "";
String bottomLine = "";
//BufferedReader readerForKeyFile = new BufferedReader(new FileReader("Key.java"));
StringBuilder fileString = new StringBuilder();
List<Character> topList = new ArrayList<Character>();
List<Character> bottomList = new ArrayList<Character>();
try{
String line = readerForText.readLine();
while (line!= null){
fileString.append(line);
fileString.append("\n");
line = readerForText.readLine();
}
fileString.toString().toLowerCase();
System.out.println(fileString);
topLine = keyFileReader.nextLine();
bottomLine = keyFileReader.nextLine();
//Convert top line to char array
char arrayChar1[] = topLine.toCharArray();
for(char a:arrayChar1)
{
topList.add(a);
}
//Convert bottom to char array
char arrayChar2[] = bottomLine.toCharArray();
for(char a:arrayChar2)
{
bottomList.add(a);
}
LinkedHashMap<Character,Character> keyMapper = new LinkedHashMap<Character,Character>();
for(int i = 0;i<topLine.length();++i)
{
keyMapper.put(arrayChar1[i],arrayChar2[i]);
}
//Testing that key and value pair has been read in correctly
for(Map.Entry<Character, Character> entry : keyMapper.entrySet())
{
System.out.print(entry.getKey()+ "\n" + entry.getValue());
}
//Replace letters in fileString
for(int x = 0;x<fileString.length();x++)
{
for(Map.Entry<Character, Character> entry : keyMapper.entrySet())
{
if(fileString.charAt(x)==entry.getKey())
{
fileString.setCharAt(x,entry.getValue());
}
}
}
System.out.println(fileString);
} finally{
readerForText.close();
keyFileReader.close();
}
}
大文本的示例如下所示:
vkpuu mlusvbxfs
但是,当我替换角色时,它看起来像:
wxujj xujzwzkvz
因此它没有正确替换字符
任何关于为什么这样做的解释都会很棒。 谢谢
最佳答案
问题就出在这里。
for(int x = 0;x<fileString.length();x++)
{
for(Map.Entry<Character, Character> entry : keyMapper.entrySet())
{
if(fileString.charAt(x)==entry.getKey())
{
fileString.setCharAt(x,entry.getValue());
}
}
}
这应该是
for(int x = 0;x<fileString.length();x++)
{
Character c = keyMapper.get(fileString.charAt(x));
if (c != null)
fileString.setCharAt(x, c);
}
您的方法的问题在于,通过搜索这样的条目,您可以多次更改单个字符。
例如
u -> e -> g -> j
关于java - Java中使用LinkedHashMap替换StringBuilder中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005184/