sgd sgd - 16 days ago 5
Java Question

I have a string "I love stack overflow very much" how to remove spaces between character and make groups of 8 character?

I have a string "I love stack overflow very much" how to remove spaces between character and make groups of 8 character? how to add dummy data if no of character does not divided by 8 to make group of 8?how to add dummy data to make groups of 8 characrers?

Answer
public class Run {
    public static void main(String[] args) {
        String string = "I love stack overflow very much";

        //replacing all newline and and then making tokens
        String[] words = string.replaceAll("\\s", "").split("(?<=\\G.{8})");

        for (String st : words) {
            if (st.length() == 8) { // if length of the string is 8, just print the string
                System.out.println(st);
            } else {
                System.out.print(st);

                // printing dummy characters after the final string
                for (int i = 0; i < 8 - st.length(); i++) {
                    System.out.print("X"); // assuming dummy character = X;
                }
            }
        }
    }
}

Output

Ilovesta
ckoverfl
owverymu
chXXXXXX