0

我被这个挑战困住了,任何帮助都会很棒。

'创建一个将字符串和数字数组作为参数的函数。按照索引号指定的顺序重新排列字符串中的字母。返回“重新混合”的字符串。例子

remix("abcd", [0, 3, 1, 2]) ➞ "acdb"'

我的尝试——

package edabitChallenges;

//Create a function that takes both a string and an array of numbers as arguments.
//Rearrange the letters in the string to be in the order specified by the index numbers.
//Return the "remixed" string.

public class RemixTheString {

    public static String remix(String word, int[] array) {
        char[] wordArray = word.toCharArray();

        for (int i = 0; i < array.length; i++) {        
                char ch = ' ';
                ch = wordArray[i];
                wordArray[i] = wordArray[array[i]];
                wordArray[array[i]] = ch;
        }

        String newString = new String(wordArray);
        return newString;
    }

    public static void main(String[] args) {
        System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 }));

    }
}
4

1 回答 1

5

我建议只迭代array[]输入中传递的索引,然后构建输出字符串:

public static String remix(String word, int[] array) {
    char[] wordArray = word.toCharArray();
    StringBuilder output = new StringBuilder();

    for (int i=0; i < array.length; i++) {
        output.append(wordArray[array[i]]);
    }

    return output.toString();
}

public static void main(String[] args) {
    System.out.println(remix("abcd", new int[] { 0, 3, 1, 2 }));  // adbc
}

在这里,我们使用StringBuilderwhich 公开了一种方便的append(char)方法,可以一次将一个字符添加到正在进行的字符串中。

于 2021-07-18T06:04:20.560 回答