重新混合字符串

0 java string formatting loops challenge-response

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

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

remix("abcd", [0, 3, 1, 2]) ? "acdb"'
Run Code Online (Sandbox Code Playgroud)

我的尝试——

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 }));

    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*sen 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
}
Run Code Online (Sandbox Code Playgroud)

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