Home > Mobile >  How can I move multiple character arrays to the back of an array based upon a specific index?
How can I move multiple character arrays to the back of an array based upon a specific index?

Time:11-03

I have a string "Hello, World!" that I have to convert into a char array. I then found the index of the char ',' - to which I want to create a new char array that contains " World!, Hello".

I've got the first index of the char array moved to the back - such that it prints out "ello, World!H".

How can I use my variable indexDelimiter to move the rest of the char arrays (as well as the ',') to the back? I've been looking at this problem forever, and I'm very confused as to how I could go about this.

I can't use ListArray. I has to be an Array.

public class ArrayTest {

   public static void main(String[] args) {

       String s = "Hello, World!";
       
       char[] oldCharArray = s.toCharArray();
       char[] newCharArray = new char[oldCharArray.length];
       char delimiter = ',';
       int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
       
       for (int i = 0; i < oldCharArray.length - 1; i  ) {
           newCharArray[i] = oldCharArray[i   1];
       }  
       
       newCharArray[oldCharArray.length - 1] = oldCharArray[0];
       
       for (int i = 0; i < newCharArray.length; i  ) {
          System.out.print(newCharArray[i]);
       } 
// This prints out "ello, World!H" but I want " World!, Hello"
  }
}

CodePudding user response:

This code will produce "World!,Hello", take a look and see if it meets your needs.

public static void main(String args[]) {
        String s = "Hello, World!";
       
       char[] oldCharArray = s.toCharArray();
       char[] newCharArray = new char[oldCharArray.length];
       char delimiter = ',';
       int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
       int i = 0;
       for (i = 0; i < oldCharArray.length-indexDelimiter-1; i  ) {
           newCharArray[i] = oldCharArray[indexDelimiter   i   1];
       }
       newCharArray[i] = delimiter;
       i  ;
       int j = i;
       while (i < oldCharArray.length) {
           newCharArray[i] = oldCharArray[i - j];
           i  ;
       }  
       System.out.println(newCharArray);
    }

CodePudding user response:

If you mean backward, you can reverse the by splitting it first

public char[] reverse_comma_split(String str) {
      String[] spl = str.split(",");
      String reversed = new String();
      for (int i = spl.length - 1; i >= 0; i--) {
          reversed  = spl[i];
          if (i != 0)
            reversed  = ", ";
      }
      return reversed.toCharArray();
}

Calling reverse_comma_split("Hello, world!") would return a char array of " world!, Hello"

However, if you insist to get uppercase char in every split, you can modify the loop in which spl[i] to spl[i].substring(0, 1).toUpperCase() spl[i].substring(1)

  •  Tags:  
  • java
  • Related