简体   繁体   中英

How do I break a string into groups of letters with a loop in Java?

I have to write a method which breaks a string into groups. The user should give the amount of letters per group and the function should return a string that consists of the input string broken into groups. For instance, function(“HELLOYOU”, 2) would return “HE LL OY OU”.

You can use String.split() to break the string into an array of individual letters, and then combine pairs of letters, or larger groups, etc.

Here is some example code:

String[] splitInParts(String input, int size) {
    String[] letters = input.split("");
    String[] output = new String[letters / size];

    for (int i = 0; i < output.length; i++) {
        output[i] = "";
        for (int j = 0; j < size; j++) {
            output[i] = output[i] + letters[size * i + j];
        }
    }

    return output;
}

There is a lot of boilerplate code missing, for example, checking that loop parameters are in range, checking strings are not null, etc. However this is a rough idea of how you could go about doing it.

You can move the characters of input String to a new String and put whitespaces on every step that equals to "size":

String function(String input, int parts) {
    StringBuilder result = new StringBuilder();
    int partCounter = 0;
    for (int i = 0; i < input.length(); i++) {
        partCounter++;
        result.append(input.charAt(i));
        if (partCounter == parts){
            result.append(" ");
            partCounter = 0;
        }
    }

    return result.toString();
}

You could use the below code that takes in a String instance and aN int defining the number of characters to split based on. And then use the String instances split method .

public static String[] split(String input, int len){
    // To prevent any NullPointerException being thrown
    if (StringUtils.isEmpty()) {
        return null;
    }
    // Split the input string based on a regex pattern
    return input.split(String.format("(?<=\\G.{%1$d})", len));
}

The Regular Expression that is being used here is (?<=\\\\G.{%1$d}) which based on len being 2 would become (?<=\\\\G.{2}) . So this means it would split every 2 characters. So the output for a string of HELLOWORLD would be HE , LL , OW , OR , LD .

If you wanted to join those into one String separated by a space you could using the StringUtils#join method .

String joinedString = StringUtils.join(split, StringUtils.SPACE);

Which would produce "HE LL OW OR LD" .

So an all in one method would be:

public static String separateNthCharacter(String input, int len) {
    // To prevent any NullPointerException being thrown
    if (StringUtils.isEmpty()) {
        return StringUtils.EMPTY;
    }

    String[] split = input.split(String.format("(?<=\\G.{%1$d})", len));
    return StringUtils.join(split, StringUtils.SPACE);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM