0

I want the each line to split off after 20 characters have gone by but I want it to split off at the nearest space so the sentence has only whole words.

This is the code that I have:

//I have imported the scanner util above this.
System.out.println("Please input a word: ");
            Scanner stringScanner = new Scanner(System.in);
            String input = stringScanner.nextLine();
        
         int numberOfCharacters = 20;
        
         for (int i = 0; i < input.length(); i += numberOfCharacters) {
             String part = input.substring(i, Math.min(input.length(), i + numberOfCharacters));
             System.out.println(part);
         }
     }
}

This is the output I get:

Please input a sentence: 
hello there, I am doing some coding!

hello there, I am do
ing some coding!

This is what I want:

Please input a sentence: 
hello there, I am doing some coding!

hello there, I am   
doing some coding!

I am not sure how to get this to work. Thank you for any anwers.

1 Answers1

0

It seems like you would benefit more from a bit of direction, as opposed to a canned solution since you're still learning, so I'll just give you a bit of structure and some tools, and hopefully you can work out the actual code on your own.

You can iterate through the characters of a String using the .charAt() method.

for(int pos = 0; pos < someString.length(); pos ++)
{
    System.out.println(someString.charAt(pos));
}

But your requirement, stated simply, is finding the first space character at or before the twentieth character.

So what if you decided to count backwards? Start at position 20 (which is actually the 21st character since we're dealing with an index starting at 0).

for(int pos = numberOfCharacters; pos >= 0; pos --)
{
    if(someString.charAt(pos) == ' ')
    {
        // get the substring from 0 to pos for one line
        // get the substring from pos + 1 to end of line for the next
    }
}

If that's a space, you know you can substring your input string right there. If not, move backward one character and see if it's a space, and so on. The only way this "breaks" is if someone enters a short string with two or more consecutive spaces, but I can't tell you how to handle that because it's a design decision you'll have to make on your own.

If you want to get fancy, you can also implement this function as a recursion which fits this function naturally, but that's for another question.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56