我目前有一个程序,可以将字符串的标记单独转换为它们的 Piglatin 对应项。但是,程序需要将它们插入到原来的字符串中,其中包含所有原始字符。
Hasta la vista baby. - the Terminator.
Hasta
astaHay
la
alay
vista
istavay
baby
abybay
the
ethay
Terminator
erminatorTay
这些是所有单词及其转换。我尝试了一种直接将它们放回去的方法,但是考虑到丢失的字符和不同的长度使我很难做到这一点。我尝试根据每个标记加起来的长度插入字符,但当存在超过 1 个空白字符时,就会遇到麻烦。我如何将这些单词插入到字符串中,使其看起来像这样:
Astahay alay istavay abybay. - ethay Erminatortay
PigOrig = key.readLine();
String[] PigSplit = PigOrig.split("\\W+");
for(int i = 0; i < PigSplit.length; i++)
{
if(PigSplit[i] != null)
{
FinalStr += Piggy.vowelOut(PigSplit[i]); // VowelOut returns the converted word only, no trailing whitespace or punctuation
lengthtot += PigSplit[i].length();
FinalStr += PigOrig.charAt(lengthtot); // attempt at adding up the words and inserting the original punctuation that was in the string PigOrig
lengthtot ++;
}
}
最佳答案
如果我理解你的问题,那就是“如何用字符串中的翻译替换每个单词?”最简单的方法是使用String.replace
。
因此,如果您创建了 translate
方法,那么您可以执行以下操作:
String line = key.readLine();
for (String word: line.split("\\W+"))
line = line.replace(word, translate(word));
这种方法的优点是您可以替换原始字符串中的单词,而不是再次将单词重新组合在一起。
另请注意,仅使用模式匹配可能会更容易翻译。例如:
private String translate(String word) {
Matcher match = Pattern.compile("(\\w*)([aeiou]\\w*)").match(word);
if (match.matches())
return match.group(2) + match.group(1) + "ay";
else
return word;
}
关于Java将修改后的标记添加到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40231209/