所以我必须编写一个程序,到目前为止,我已经有一些运气让程序做我想要的。首先,我应该创建一个java程序,它接受像“tan”这样的单词并交换a和n来给你“tna”。虽然,如果我到目前为止将aardvark这个词放入程序中,它会正确地交换所有a,但它会在最终输出中切断k。如果有人可以提供帮助,那将非常感激。
String word = "aardvark";
String combined = "";
for (int i = 0, j = 1; i < word.length() && j < word.length(); i++, j++) {
if (word.substring(i, j).equals("a")) {
combined = combined + word.substring(i + 1, j + 1)+ word.substring(i, j);
i++;
j++;
}
else {
combined = combined + word.substring(i, j);
}
}
System.out.print(combined);
答案 0 :(得分:1)
这样做你想要的,保持简单:
String word = "aardvark";
char[] symbols = word.toCharArray();
for (int i = 0; i < symbols.length - 1; ++i) {
if (symbols[i] == 'a') { // have to swap with the next symbol
symbols[i] = symbols[i + 1];
symbols[i + 1] = 'a';
++i;
}
}
String scrambled = new String(symbols);
System.out.println("scrambled = " + scrambled); // aardvrak