Home > Software design >  How to move the first N elements in a char array to the end in Java
How to move the first N elements in a char array to the end in Java

Time:07-18

I have to take a sentence from a document and separate each word and if the word is even, take the first half and put them at the end of the word. If it is odd, take the first half 1 and put them at the end of the word. I have figured out for the most part the even-numbered words and those are displaying correctly, I am having trouble with the odd-numbered words like the and wonderful. Here's what I have so far.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class Exercise5 {

    public static void main(String[] args) throws IOException {
        FileInputStream inputFile = new FileInputStream("input.in");
        Scanner scnr = new Scanner(inputFile);
        String sentence = scnr.nextLine();
        String[] inputSentence = sentence.split(" ");
        int i;
        String arrayOutput = null;
        char[] c = null;

        for (String arrayInput : inputSentence) {
            c = arrayInput.toCharArray();
            if (arrayInput.length() % 2 == 0) {
                for (i = 0; i < arrayInput.length() / 2; i  ) {
                    char temp = c[i];
                    c[i] = c[i   (arrayInput.length() / 2)];
                    c[i   (arrayInput.length() / 2)] = temp;
                }
            } else if (arrayInput.length() % 2 == 1) {
                for (i = 0; i < (arrayInput.length() / 2);   i) {
                    char temp = c[i];
                    c[i] = c[i   (arrayInput.length() / 2)   1];
                    c[i   (arrayInput.length() / 2)   1] = temp;
                }
            }
            arrayOutput = new String(c);
            System.out.println(arrayOutput);
        }
    }
 }

CodePudding user response:

This can be done much simpler using substring and taking advantage of integer division.

int x = (word.length()   1) / 2;
word = word.substring(x)   word.substring(0, x);

The reason it works is because if the word length l is even then l/2 is the same as (l 1)/2. And if it is odd then (l 1)/2 is what we want.

Maybe also worth mentioning is that substring(a, b) in Java doesn't include the end index b. This has the advantage that the length of the resulting string is b - a.

  •  Tags:  
  • java
  • Related