Is it possible to group a string every nth character?
For example, suppose I have a string containing the following: "Hello how are you"
What I'm trying to do is if the user inputs 4, then based on the integer, break into 4 groups and assign those to strings.
1 2 3 4 1 2 3 4 1 2 3 4 1 2
H E L L O H O W A R E Y O U
All the letters that has 1 assigned will be group 1, similarly, all the letters that has 2 assigned will be group 2.
Group 1 - "HOAO", Group 2 - "EHRU", Group 3 - "LOE", Group 4 - "LWY"
Below is what I have so far
import java.util.*;
class groupChar {
static void groupLetters(String str, int n) {
String result="";
for(int i = 0; i < str.length(); i = i + n){
result = result + str.charAt(i);
}
System.out.println(result);
}
public static void main(String[] args) {
Scanner inputMessage = new Scanner(System.in);
System.out.println("Enter string : ");
String message = inputMessage.nextLine();
System.out.println("Enter a number : ");
Scanner inputNumber = new Scanner(System.in);
int number = Integer.parseInt(inputNumber.nextLine());
System.out.println("String is - " + message);
System.out.println("Number is - " + number);
groupLetters(message, number);
}
}
So far I'm only able to create one group based on the user input.