Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating a string into groups

I need to write a method groupify which takes 2 parameters:

  1. the string that I want to break into groups.
  2. the number of letters per group.

So, the code may print a string which consists of the input string broken into groups with the number of letters specified on the second parameters, if there aren't enough letters in the input string to fill out all the groups, it should fill the final group with "x", so if I groupify("HELLODANY",2), it must return "HE LL OD AN YX"

My code is the following:

package com.company;
import java.util.Random;

public class Main {
    public static String gropify(String message,int number) {
        String result="";
        int len =message.length();
        int s=0;
        int n=3;
        for(int x=0;x<len;++n) {
            s = s + number;
            result = result + message.substring(x,s);
        }
        return result;
    }

    public static void main(String[] args) {
        String message= "HELLODANY";
        System.out.println(gropify(message, 3));
    }
}

But I'm getting the following exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12

What should I change?

like image 539
CZarate29 Avatar asked Jul 16 '26 17:07

CZarate29


1 Answers

I would prefer a StringBuilder over many String concatenations (those create temporary immutable String instances). Next, you can test if the current index is evenly divisible by number, if it is then you add a space; then append the actual character to the StringBuilder. Finally, add padding by calculating the remainder of the message length divided by number - append that many X(s). Like,

public static String gropify(String message, int number) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < message.length(); i++) {
        if (i != 0 && i % number == 0) {
            sb.append(' ');
        }
        sb.append(message.charAt(i));
    }
    int pad = message.length() % number;
    for (int i = 0; i < pad; i++) {
        sb.append('X');
    }
    return sb.toString();
}

Note that your current approach is flawed, you are adding to s in the loop body, when you hit 12 you exceed the length of your message.

like image 59
Elliott Frisch Avatar answered Jul 19 '26 07:07

Elliott Frisch