Search code examples
javastringsplitter

How do you take a string from user and split it up?


I am trying to write a Java program that:

  • Store the string in a variable called inputStr and the integer in a variable called inputInt.

  • Pass inputStr and inputInt to a method called splitter. The splitter method splits the input

  • string by exactly inputInt characters at a time and prints each in a line. Only the splits that

  • have exactly inputInt characters should be printed.

This is the code I have so far:

 public static void main(String[] args) {
 Scanner keyboard = new Scanner(System.in);
 System.out.print("What is your Phrase? "); 
 String inputStr;
 inputStr = keyboard.nextLine();
   System.out.println("Enter a Integer");
 int inputInt;
 inputInt=keyboard.nextInt();

 for(int i =1;i<20;i++){

 inputStr.substring(0, inputInt);



 }

The program should look like this:
Please enter a string: ThisIsAnExample
Please enter an integer: 3
Thi
sIs
AnE
xam
ple

Example2:
Please enter a string: ThisIsAnotherExample
Please enter an integer: 6
ThisIs
Anothe
rExamp

Note that in example 2, the last 2 characters (“le”) are not printed since they don’t have 6 characters.


Solution

  • You can change the code Like This:

    public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("What is your Phrase? "); 
            String inputStr;
            inputStr = keyboard.nextLine();
            System.out.println("Enter a Integer");
            int inputInt;
            inputInt=keyboard.nextInt();
            for(int i =0;i<inputStr.length();i+=inputInt){     
                if(i+inputInt < inputStr.length())
                    System.out.println(inputStr.substring(i,i+inputInt));
                else
                    System.out.println(inputStr.substring(i,inputStr.length()));
            }
        } 
    

    for(int i =0;i<inputStr.length();i+=inputInt) Increments the loop the number entered by the user times. inputInt

    The print the string from that i position to the i+inputInt to break the string.

    The If and else loop used to avoid the StringIndexOutOfBoundsException beacuse consider if a user want break 5 letter word in 3 letters. The final string will have 2 letters and will throw StringIndexOutOfBoundsException Exception.

    -----------------------------------EDIT --------------------------

    To match the Example 2:

    inputInt=keyboard.nextInt();
            for(int i =0;i<inputStr.length();i+=inputInt){     
                if(i+inputInt < inputStr.length())
                    System.out.println(inputStr.substring(i,i+inputInt));
    
            }