我有这个:
for (String[] aZkratkyArray1 : zkratkyArray) {
String oldString = " " + aZkratkyArray1[0] + " ";
String firstString = aZkratkyArray1[0] + " ";
String newString = " " + aZkratkyArray1[1] + " ";
System.out.println(newString);
System.out.println(fileContentsSingle);
fileContentsSingle = fileContentsSingle.replaceAll(oldString, newString);
if (fileContentsSingle.startsWith(firstString)) {
fileContentsSingle = aZkratkyArray1[1] + " " + fileContentsSingle.substring(firstString.length(),fileContentsSingle.length());
}
}
fileContentsSingle只是一些常规字符串,aZkratkyArray是带有缩短单词的数组,例如:
ht,你好
ru,你是谁
所以当fileContentsSingle = ht我是机器人
它应该结束:你好,我是机器人
或当fileContentsSingle =我是机器人hru
它应该结束:我是机器人,你是谁
但是当我在该迭代之后或在此过程中sysout fileContentsSingle时,字符串永远不会更改。
我尝试了replace和replaceAll,我尝试了可能想到的一切。
错误在哪里?
编辑:
这是我导入数组的方式:
String[][] zkratkyArray;
try {
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("zkratky.csv"));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
lineNumberReader.close();
FileReader fileReader = new FileReader("zkratky.csv");
BufferedReader reader = new BufferedReader(fileReader);
zkratkyArray = new String[lines + 1][2];
String line;
int row = 0;
while ((line = reader.readLine()) != null) {
String[] array = line.split(",");
for (int i = 0; i < array.length; i++) {
zkratkyArray[row][i] = array[i];
}
row++;
}
reader.close();
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("Soubor se zkratkami nenalezen.");
zkratkyArray = new String[0][0];
}
最佳答案
您的代码将针对“我是机器人”正确工作。如果在fileContentsSingle
循环之后打印for
,它将打印您希望打印的内容:
final String[][] zkratkyArray = new String[2][];
zkratkyArray[0] = new String[] { "ht", "hello there" };
zkratkyArray[1] = new String[] { "wru", "who are you" };
String fileContentsSingle = "ht I am robot";
for (String[] aZkratkyArray1 : zkratkyArray) {
String oldString = " " + aZkratkyArray1[0] + " ";
String firstString = aZkratkyArray1[0] + " ";
String newString = " " + aZkratkyArray1[1] + " ";
fileContentsSingle = fileContentsSingle.replaceAll(oldString, newString);
if (fileContentsSingle.startsWith(firstString)) {
fileContentsSingle = aZkratkyArray1[1] + " "
+ fileContentsSingle.substring(firstString.length(), fileContentsSingle.length());
}
}
System.out.println(fileContentsSingle); // prints "hello there I am robot"
关于“我是机器人hru”,它将不起作用,因为“ hru”在
String
的末尾,并且后面没有空格,并且您要替换的String
是“ hru”(在和后)。由于不使用正则表达式,因此不需要
replaceAll()
,而可以使用replace()
。使用正则表达式,您可以做一个更通用的解决方案,可在生产线中的任何地方工作:
final String[][] zkratkyArray = new String[2][];
zkratkyArray[0] = new String[] { "ht", "hello there" };
zkratkyArray[1] = new String[] { "wru", "who are you" };
String fileContentsSingle = "ht I am robot wru";
for (String[] aZkratkyArray1 : zkratkyArray) {
fileContentsSingle = fileContentsSingle.replaceAll("\\b" + Pattern.quote(aZkratkyArray1[0]) + "\\b",
Matcher.quoteReplacement(aZkratkyArray1[1]));
}
System.out.println(fileContentsSingle); // hello there I am robot who are you