Justify text in Java

后端 未结 9 1382
闹比i
闹比i 2020-12-21 16:33

I have to read in an integer which will be the length of the succeeding lines. (The lines of text will never be longer than the length provided).

I then have to read

9条回答
  •  不知归路
    2020-12-21 17:19

    The way I would go about this is to use a loop with regular-expression replacements.

    1. Replace all spaces with underscores.
    2. For each char necessary to get the length up to the desired length, replace a single underscore with a two underscores. Use regular expressions to make sure that these replacements only happen where the desired number of underscores does not already exist. See JavaDoc for .ReplaceFirst(). You'll also need to account for the possibility that you have to replace double-underscores with triples.

    After you do the initial replacement, I'd suggest you use a while loop, bounded on the length of the string being less than the target size. Initialize int numUnderscores = 1; outside of the while. Then the steps inside the loop will be:

    1. Build the replacement pattern. This should be something like "/[^_](_{" + numUnderscores + "})[^_]/" which says "any char that is not an underscore, followed by numUnderscores instances of the underscore char, followed by any char that is not an underscore"
    2. Call .ReplaceFirst() to perform the replacement
    3. Check to see if the string contains any remaining instances of the current number of underscores; if it does not, then you must increment numUnderscores

    Obviously, since this is a homework problem, I'm leaving the actual process of writing the code as an exercise. If you have specific questions about some piece of it, or about some component of the logic structure I described, just ask in comments!

    The benefit of doing things this way is that it will work for any size string, and is very configurable for different situations.

提交回复
热议问题