Njena
Njena

Reputation: 301

Reordering a String according to given indexes

if the input string="india" the out put will be "niida" this means the indexex positions are {1,0,3,2,4};

class ReorderSt{
static String []arr=new  String[]{"Technoarck"};
    static int [] index= new int[]{1,0,3,2,5,4,7,6,8};

    static void record(){
        String []temp= new String[arr.length];
        //arr[i] should be present at index[i]
        for (int i = 0; i < arr.length; i++) 
        temp[index[i]]=arr[i];
        //copy temp to array
        for (int i = 0; i < temp.length; i++) {
            arr[i]=temp[i];
            index[i]=i;
        }

    }
    public static void main(String[] args) {
       record();
        System.out.println("Recorded array is");
        System.out.println(Arrays.toString(arr));
        System.out.println("modified index array is");
        System.out.println(Arrays.toString(index));
    }

}

i got error ArrayIndexOutofbond in this line temp[index[i]]=arr[i];

Upvotes: 0

Views: 234

Answers (2)

Arasn
Arasn

Reputation: 158

Technoarck has length 10. Index from 0 to 9 But the input index is upto 8 only there. Correct it and try.

Since it is an array of string with one string in it. arr [1] wil throw array out of bound. It’s a string array not character array

Or use temp[index[i]]= arr[0].charAt[i]

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

That is quite a bit of code, and you don't need any arrays for your desired transform. Take an input String, and an array of indices and use a StringBuilder to construct a new String value using the indices and String.charAt(int) to append values. Something like,

String input = "Technoarck";
int[] index = {1,0,3,2,5,4,7,6,8};
System.out.printf("Recorded input is %s%n", input);
StringBuilder sb = new StringBuilder();
for (int i : index) {
    sb.append(input.charAt(i));
}
System.out.printf("Modified output is %s%n", sb.toString());

Upvotes: 1

Related Questions