Issue
So here is an example
String str = 'Java is a high-level programming language originally developed by Sun Microsystems and released in 1995'
Trying to come up with method that will split the string based on the index value defined but if that index is in the middle of the word it will split it after the word.
So if say the index is 31 , that would actually split the sentence like this (each line is 31 characters long)
Java is a high-level programmin
g language originally developed
by Sun Microsystems and release
d in 1995
Notice how the word "programming" and "released" were split. If the character at index is not a space, I would like to advance the to the next space and then split the string. For example:
Java is a high-level programming
language originally developed by
Sun Microsystems and released in
1995
In the above illustration, no word was split (each line is at least 31 characters long).
Solution
Here is one way. No explicit loops involved.
- find midpoint of string.
- find first space after mid point.
- find first space before mid point.
- select split position based on distance from midpoint.
int mid = str.length()/2;
int indexBeyondMid = str.indexOf(' ',mid);
int indexBeforeMid = str.substring(0,mid).lastIndexOf(' ');
int splitPoint = mid - indexBeforeMid < indexBeyondMid - mid
? indexBeforeMid
: indexBeyondMid;
String firstHalf = str.substring(0,splitPoint);
String secondHalf = str.substring(splitPoint+1); // ignores leading space.
System.out.println(firstHalf);
System.out.println(secondHalf);
The above will split as evenly as possible. If you want to just split on the first space after the mid point, then just split on indexBeyondMid
and forget the rest.
If you want to split a line as optimally as possible to a specified linewidth, you can do it like this.
int lineWidth = 19;
while (!str.isBlank()) {
lineWidth = lineWidth > str.length() ? str.length() : lineWidth;
int indexBeyondMid = str.indexOf(' ',lineWidth);
int indexBeforeMid = str.substring(0,lineWidth).lastIndexOf(' ');
int splitPoint = lineWidth - indexBeforeMid < indexBeyondMid - lineWidth
? indexBeforeMid
: indexBeyondMid;
if (splitPoint < 0) {
System.out.println(str);
break;
}
System.out.println(str.substring(0, splitPoint));
str = str.substring(splitPoint+1);
}
prints
Hey I am string that
will be split but
remember i will not
be cut in the middle
of the word
Answered By - WJS
Answer Checked By - Timothy Miller (JavaFixing Admin)