Package Torello.Java
Class StrPrint
- java.lang.Object
-
- Torello.Java.StrPrint
-
public class StrPrint extends java.lang.Object
Hi-Lited Source-Code:- View Here: Torello/Java/StrPrint.java
- Open New Browser-Tab: Torello/Java/StrPrint.java
-
-
Constructor Summary
Constructors Constructor StrPrint()
-
Method Summary
Abbreviate Input String's Modifier and Type Method static String
abbrev(String s, boolean spaceBeforeAbbrev, boolean escapeNewLines, String abbrevStr, int maxLength)
static String
abbrev(String s, int abbrevPos, boolean escapeNewLines, String abbrevStr, int maxLength)
static String
abbrevEnd(String s, boolean escapeNewLines, int maxLength)
static String
abbrevEndRDSF(String s, int maxLength, boolean seeEscapedNewLinesAsText)
static String
abbrevStart(String s, boolean escNewLines, int maxLength)
static String
abbrevStartRDSF(String s, int maxLength, boolean seeEscapedNewLinesAsText)
Selectively Print Lines of Text Modifier and Type Method static String
firstNLines(String s, int n)
static String
lastNLines(String s, int n)
static String
line(String s, int pos)
static String
lineOrLines(String s, int pos, int len, String unixColorCode)
static String
newLinesAsText(String s)
static String
trimEachLine(String str)
Print a List, Vertically Top to Bottom Modifier and Type Method static <ELEM> String
printListAbbrev(ELEM[] arr, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
static <ELEM> String
printListAbbrev(ELEM[] list, IntTFunction<? super ELEM,String> listItemPrinter, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
static <ELEM> String
printListAbbrev(Iterable<ELEM> list, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
static <ELEM> String
printListAbbrev(Iterable<ELEM> list, IntTFunction<? super ELEM,String> listItemPrinter, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
-
-
-
Constructor Detail
-
StrPrint
public StrPrint()
-
-
Method Detail
-
newLinesAsText
public static java.lang.String newLinesAsText(java.lang.String s)
Converts every line-character ('\n'
) - and any white-space before or after that character, into theString
-"\\n"
- which is the actual two character sequence of a back-slash ('\'
), followed by the letter'n'
.
After new-line characters are replaced, the method will remove any duplicate spaces that are present in theString
, and reduce them to a single space characterInput String
Returned String
"Hello World" "Hello World" "Hello \t World" "Hello World" "Hello World\n" "Hello World\\n" "Hello World \n\t \n" "Hello World\\n\\n" "Hello Today!\nHow Are You?" "Hello Today!\\nHow Are You?" "Hello,\n Testing 1, 2, 3\n" "Hello,\\nTesting 1, 2, 3\\n" "Hello,\n Testing 1, 2, 3 \n\t\t\t" "Hello,\\nTesting 1, 2, 3\\n" "\n" "\\n" "\n \t" "\\n" "\n\t \n\t \n\t " "\\n\\n\\n"
This method is used in printing Java Source Code to a terminal - in an abbreviated way! After this method is finished, java-source-as-text is actually still look readable, and can be printed in a table of methods on a page. It is used in the Java Doc Upgrader tool, and makes printing up both method-signatures and method bodies quite a bit easier.
For a better understanding of the use and application of this function, please take a look at the'toString'
methods:Method.toString()
,Constructor.toString()
,Field.toString()
andAnnotationElem.toString()
FINALLY: This method uses regular-expressions, rather performing an in-place replacement using afor
orwhile
loop. It sacrifices a little efficiency for brevity. Also, the replacement used in theString.replaceAll
method was tested, thouroughly. The quadruple-backslash'n'
is actually necessary! The first-escape used is to communicate with the Java-Compiler, and the second round of escaping is communicating with the Regular Expression Processor. *- Parameters:
s
- Anyjava.lang.String
, preferably one with multiple lines of text.- Returns:
- A
String
, where each line of text has been "trimmed", and the two character sequence"\\n"
inserted in-between each line. - See Also:
abbrevStartRDSF(String, int, boolean)
,abbrevEndRDSF(String, int, boolean)
- Code:
- Exact Method Body:
return s .replaceAll( // White-Space-Except-Newline, THEN newline, THEN White-SpaceExcept-Newline "[ \t\r\f\b]*\n[ \t\r\f\b]*", // Replace Each Occurence of that with: // == COMPILES-TO ==> "\\n" == REG-EX-READS ==> BackSlash and letter 'n' "\\\\n" ) // == COMPILES-TO ==> "\s+" == REG-EX-READS ==> 'spaces' .replaceAll("\\s+", " ") // Don't forget about leading and trailing stuff... .trim();
-
abbrevStartRDSF
public static java.lang.String abbrevStartRDSF (java.lang.String s, int maxLength, boolean seeEscapedNewLinesAsText)
Convenience Method
RDSF: Remove Duplicate Spaces First
Invokes:StringParse.removeDuplicateSpaces(String)
Or Invokes:newLinesAsText(String)
Finally:abbrevStart(String, boolean, int)
- Code:
- Exact Method Body:
// false is passed to 'abbrevStart' parameter 'escapeNewLines' because in both scenarios // of this conditional-statement, the new-lines have already been removed by the previous // method call. // // both 'removeDuplicateSpaces' and 'newLinesAsText' remove the new-lines return seeEscapedNewLinesAsText ? abbrevStart(newLinesAsText(s), false, maxLength) : abbrevStart(StringParse.removeDuplicateSpaces(s), false, maxLength);
-
abbrevEndRDSF
public static java.lang.String abbrevEndRDSF (java.lang.String s, int maxLength, boolean seeEscapedNewLinesAsText)
Convenience Method
RDSF: Remove Duplicate Spaces First
Invokes:StringParse.removeDuplicateSpaces(String)
Or Invokes:newLinesAsText(String)
Finally:abbrevEnd(String, boolean, int)
- Code:
- Exact Method Body:
// false is passed to 'abbrevStart' parameter 'escapeNewLines' because in both scenarios // of this conditional-statement, the new-lines have already been removed by the previous // method call. // // both 'removeDuplicateSpaces' and 'newLinesAsText' remove the new-lines return seeEscapedNewLinesAsText ? abbrevEnd(newLinesAsText(s), false, maxLength) : abbrevEnd(StringParse.removeDuplicateSpaces(s), false, maxLength);
-
abbrevStart
public static java.lang.String abbrevStart(java.lang.String s, boolean escNewLines, int maxLength)
Convenience Method
Invokes:abbrev(String, int, boolean, String, int)
Passes:'0'
to parameter'abbrevPos'
, forcing the abbreviation to occur at the start of theString
(if long enough to be abbreviated)- Code:
- Exact Method Body:
return abbrev(s, 0, escNewLines, null, maxLength);
-
abbrev
public static java.lang.String abbrev(java.lang.String s, int abbrevPos, boolean escapeNewLines, java.lang.String abbrevStr, int maxLength)
This will abbreviate anyString
using either the ellipsis ('...'
), or some other use provided abbreviation-String
- as long as the providedString
is longer than'maxLength'
. When's'
is, indeed, longer than'maxLength'
the returned-String
will contain the ellipsis abbreviation beginning atString
-index'abbrevPos'
.
You have the option of asking that new-line characters ('\n'
) be escaped into the two-characterString: "\\n"
. This optional is provided so that the output may fit on a single-line, for readability purposes. It will look somewhat like an escapedJSON
file, which also substitues'\n'
characters for the 'escaped' version"\\n"
. Note that when this occurs, the replaced-String
actually only contains two characters, not three, since the first back-slash your are looking right here is, itself, an escape character!- Parameters:
s
- This may be any Java (non-null)String
abbrevPos
- This parameter is used to indicate where the abbreviation-String
should occur - if thisString 's'
is long enough to be abbreviated. For instance, if'0'
(zero) were passed to this parameter, and's'
were longer than parameter'maxLength'
, then an ellipsis would be appended to the beginning of the returned-'String'
. (Or, if some other'abbrevStr'
were specified, that other abbreviation would be appended to the beginning of the returned-String
)escapeNewLines
- When this parameter is set toTRUE
, any new-lines that would be included in the outputString
are replaced with the (two-character)"\\n"
notation, instead.
NOTE: When this parameter is passedTRUE
, the output-String
will have one fewer character for each'\n'
(newline) that was present inside the original input-String
(as long as the input-String
is, indeed, being abbreviated).
If's'
is already shorter than'maxLength'
and can fit even with the escaped-newlines, then the returned-String
will be the same as the input (because it is not being abbreviated) - except that any & all new-line characters will have been escaped.abbrevStr
- This parameter may be null, and if or when it is, it will be ignored. The default abbreviation-String
is the three-dot ellipsis ('...'
). When this parameter is passed a non-null value, its value will be used as the "abbreviation-String
" - instead of the'...'
standard-ellipsis notation.maxLength
- This is the longest value allowed for the returned-String
. When an input-String
(parameter's'
) is passed that is longer than the value of'maxLength'
, then theString
that is returned will be abbreviated to length'maxLength'
.
NOTE: Whenever anyString
is passed that has a length that is less than'maxLength'
, the original input-String
, itself, shall be returned as the result of this function (without any ellipsis or abbreviation).- Returns:
- If the input
String
has a length less-than'maxLength'
, then it is returned, unchanged. If the input contained new-line characters, and you have requested to escape them, that replacement is performed first (which makes the originalString
} longer). Then, if theString
is longer than'maxLength'
, it is abbreviated, and either the default ellipsis or the user-provided'abbrevStr'
are inserted at location'abbrevPos'
and returned.
If, after the new-line escape-replacement, the returned-String
would not be longer than'maxLength'
, then that escaped-String
is returned, as is (without any elliptical-characters). - Throws:
java.lang.IllegalArgumentException
- If the value for'maxLength'
is negative, or if it is less than the length of the abbreviation.
Specifically, if'maxLength'
isn't even long enough to fit the abbreviation itself, then this exception will throw.
If the value passed to'abbrevPos'
is negative or longer than the value passed to'maxLength'
minus the length of the ellipsis-String
, then this exception will also throw.- Code:
- Exact Method Body:
if (maxLength < 0) throw new IllegalArgumentException ("The value passed to 'maxLength' " + maxLength + ", may not be zero or negative."); if (abbrevPos < 0) throw new IllegalArgumentException ("You have passed a negative value to parameter 'abbrevPos': " + abbrevPos); if (abbrevStr == null) abbrevStr = "..."; int SLEN = s.length(); int ALEN = abbrevStr.length(); if ((abbrevPos + ALEN) >= maxLength) throw new IllegalArgumentException( "The value passed to parameter 'abbrevPos', " + abbrevPos + ", added to the length " + "of the abbreviation-ellipsis String, \"" + abbrevStr + "\", is longer than the " + "value provided to parameter 'maxLength' " + maxLength ); if (! escapeNewLines) if (SLEN <= maxLength) return s; char[] cArr = new char[maxLength]; // NOTE: Two lines ago, if the input string 's' actually fit, it would already have been // returned (in the case that escaping new-lines was NOT requested) if (! escapeNewLines) { s.getChars(0, abbrevPos, cArr, 0); abbrevStr.getChars(0, ALEN, cArr, abbrevPos); s.getChars(SLEN - (maxLength - (abbrevPos + ALEN)), SLEN, cArr, abbrevPos + ALEN); return new String(cArr); } // Beginning Here: It has been determined that new-lines are to be escaped.... int targetPos=0, srcPos=0, oldSrcPos=0; char c; while ((targetPos < abbrevPos) && (srcPos < SLEN)) // When / If a new-line character is encountered, just insert the "\\n" // substring. Otherwise, normally copy the next character in the source-string if ((c = s.charAt(srcPos++)) == '\n') { cArr[targetPos++] = '\\'; if ((targetPos < cArr.length) && (targetPos < abbrevPos)) cArr[targetPos++] = 'n'; } else cArr[targetPos++] = c; // This is the case where the String was short enough to fit before the // abbrev-pos. if (srcPos == SLEN) return new String(cArr, 0, targetPos); // In this loop, the iteration is done in reverse. It starts at the end of the // source-String, and at the end of the out char-array, and works backward. // LOOP CONTINUES: Continues until the 'abbrevPos' has been reached. oldSrcPos = srcPos; srcPos = SLEN - 1; targetPos = cArr.length - 1; while ((targetPos >= abbrevPos) && (srcPos >= oldSrcPos)) // Here, we need to make sure not to over-write the if ((c = s.charAt(srcPos--)) == '\n') { cArr[targetPos--] = 'n'; if (targetPos >= abbrevPos) cArr[targetPos--] = '\\'; } else cArr[targetPos--] = c; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // CASE 1: The String didn't fit into the 'maxLength' specified array, so it *DOES* // need to be abbreviated. // Copy the abbreviation-string into cArr, and return it. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (srcPos >= oldSrcPos) { abbrevStr.getChars(0, ALEN, cArr, abbrevPos); return new String(cArr); } // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // CASE 2: The String did fit (even with escaped '\n' ==> "\\n") // **AND** It fit PRECISELY-EXACTLY into the output char-array // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if ((targetPos == (abbrevPos-1)) && (srcPos == (oldSrcPos-1))) return new String(cArr); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // CASE 3: There is extra-room in the output-String // This means that the copy which just occurred in the previous loop was wrong // There isn't an easy way to avoid this (other than counting new-lines first) // Instead, shift the char-array, and then return it // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** srcPos = targetPos + 1; targetPos = abbrevPos; while (srcPos < cArr.length) cArr[targetPos++] = cArr[srcPos++]; return new String(cArr, 0, targetPos);
-
abbrevEnd
public static java.lang.String abbrevEnd(java.lang.String s, boolean escapeNewLines, int maxLength)
Convenience Method
Invokes:abbrev(String, boolean, boolean, String, int)
Parameter:spaceBeforeAbbrev
set toFALSE
Abbreviates: Default ellipsis ('...'
) are placed at the end of theString
- Code:
- Exact Method Body:
return abbrev(s, false, escapeNewLines, null, maxLength);
-
abbrev
public static java.lang.String abbrev(java.lang.String s, boolean spaceBeforeAbbrev, boolean escapeNewLines, java.lang.String abbrevStr, int maxLength)
This will abbreviate anyString
using either the ellipsis ('...'
), or some other use provided abbreviation-String
, if the providedString
is longer than'maxLength'
. If the returned-String
is, indeed, abbreviated then the elliptical-abbreviationString
will be placed at the end of the returned-String
You have the option of asking that new-line characters ('\n'
) be escaped into the two-characterString: "\\n"
. This optional is provided so that the output may fit on a single-line, for readability purposes. It will look somewhat like an escapedJSON
file, which also substitues'\n'
characters for the 'escaped' version"\\n"
. Note that when this occurs, the replaced-String
actually only contains two characters, not three, since the first back-slash your are looking right here is, itself, an escape character!- Parameters:
s
- This may be any Java (non-null)String
spaceBeforeAbbrev
- This ensures that for whatever variant of ellipsis being used, the space-character is inserted directly before appending the ellipsis"..."
or the user-provided'abbrevStr'
.escapeNewLines
- When this parameter is set toTRUE
, any new-lines that would be included in the outputString
are replaced with the (two-character)"\\n"
notation, instead.
NOTE: When this parameter is passedTRUE
, the output-String
will have one fewer character for each'\n'
(newline) that was present inside the original input-String
(as long as the input-String
is, indeed, being abbreviated).
If's'
is already shorter than'maxLength'
and can fit even with the escaped-newlines, then the returned-String
will be the same as the input (because it is not being abbreviated) - except that any & all new-line characters will have been escaped.abbrevStr
- This parameter may be null, and if or when it is, it will be ignored. The default abbreviation-String
is the three-dot ellipsis ('...'
). When this parameter is passed a non-null value, its value will be used as the "abbreviation-String
" - instead of the'...'
standard-ellipsis notation.maxLength
- This is the longest value allowed for the returned-String
. When an input-String
(parameter's'
) is passed that is longer than the value of'maxLength'
, then theString
that is returned will be abbreviated to length'maxLength'
.
NOTE: Whenever anyString
is passed that has a length that is less than'maxLength'
, the original input-String
, itself, shall be returned as the result of this function (without any ellipsis or abbreviation).- Returns:
- If the input
String
has a length less-than'maxLength'
, then it is returned, unchanged. If the input contained new-line characters, and you have requested to escape them, that replacement is performed first (which makes the originalString
} longer). Then, if theString
is longer than'maxLength'
, it is abbreviated, and either the default ellipsis or the user-provided'abbrevStr'
are are appended to the end and returned. - Throws:
java.lang.IllegalArgumentException
- If the value for'maxLength'
is negative, or if it is less than the length of the abbreviation plus the value of'spaceBeforeAbbrev'
.
Specifically, if'maxLength'
isn't even long enough to fit the abbreviation itself, then this exception will throw.- Code:
- Exact Method Body:
if (maxLength < 0) throw new IllegalArgumentException ("The value passed to 'maxLength' " + maxLength + ", may not be zero or negative."); // If the original String is shorter than the 'maxLength' parameter, return the original // String immediately - **UNLESS** the user has requested to replace new-line characters // with the "Escaped New-Line Sequence "\\n" if (! escapeNewLines) if (s.length() <= maxLength) return s; // The default abbreviation is just the ellipsis. if (abbrevStr == null) abbrevStr = "..."; char[] cArr = new char[maxLength]; int srcPos = 0; int targetPos = 0; char c = 0; int LEN = s.length(); int END = maxLength - abbrevStr.length() - (spaceBeforeAbbrev ? 1 : 0); if (END < 0) throw new IllegalArgumentException( "The value provided to 'maxLength' was : " + maxLength + ", but this isn't long " + "enough to even contain the abbreviation-string: \"" + (spaceBeforeAbbrev ? " " : "") + abbrevStr + "\"" ); if (! escapeNewLines) // NOTE: Here, the abbreviation will be necessary, so use 'END' instead of 'LEN' // This is because at the top, if the whole-String fit, this method would have // already returned ... if (! escapeNewLines) *above* // ALSO: More efficient at copying String-arrays than a 'for-loop' is 'getChars' s.getChars(0, targetPos = END, cArr, 0); else { while ((targetPos < maxLength) && (srcPos < LEN)) // When / If a new-line character is encountered, just insert the "\\n" // substring. Otherwise, normally copy the next character in the source-string if ((c = s.charAt(srcPos++)) == '\n') { cArr[targetPos++] = '\\'; if (targetPos < cArr.length) cArr[targetPos++] = 'n'; } else cArr[targetPos++] = c; // If every single character from the input String has been appended to the output, // then there is no need to add the abbreviation String (usually, the ellipsis '...'). // In this case, just return original-String immediately (with the escaped newlines). if (srcPos == LEN) return new String(cArr, 0, targetPos); targetPos -= (abbrevStr.length() + (spaceBeforeAbbrev ? 1 : 0)); } // NOTE: There is a (false) special-case, where there *ALREADY* IS a space before the // addition of the "ellipsis" - so it *MIGHT SEEM* you wouldn't want to add another // a second-space, unfortunately, if they have asked for a space before the // abbreviation-ellipsis, it is also inappropriate to add another character from the // original String. // LONG-STORY-SHORT: There is a (small) chance that there will be two spaces in a row here, // but in order to comply with the 'maxLength' parameter, there is no // alternative. if (spaceBeforeAbbrev) cArr[targetPos++] = ' '; abbrevStr.getChars(0, abbrevStr.length(), cArr, targetPos); return new String(cArr, 0, targetPos + abbrevStr.length());
-
printListAbbrev
public static <ELEM> java.lang.String printListAbbrev (java.lang.Iterable<ELEM> list, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
Convenience Method
Invokes:printListAbbrev(Iterable, IntTFunction, int, int, boolean, boolean, boolean)
Passes:Object.toString()
to'listItemPrinter'
- Code:
- Exact Method Body:
return printListAbbrev( list, (int i, Object o) -> o.toString(), lineWidth, indentation, seeEscapedNewLinesAsText, printNulls, showLineNumbers );
-
printListAbbrev
public static <ELEM> java.lang.String printListAbbrev (java.lang.Iterable<ELEM> list, IntTFunction<? super ELEM,java.lang.String> listItemPrinter, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
Converts any javaArray
into a vertically printed list. This method is very suited to printing out lists of objects whosetoString()
method may return a very long / extendedString
, but whose abbreviation would perfectly suffice for a cursory or circumspect viewing of the list contents.
The "vertically printed" list will contain the results of invoking'listItemPrinter'
on an element of the input'list'
parameter. Afterwards, that resultantString
is abbreviated and trimmed usingabbrevEndRDSF
and alsotrimLeft
so that it fits on a single line of text.
The length of each line in the "Vertically Printed List" will not be longer than'indentation'
(space) characters, plus the value passed to'lineWidth'
.- Parameters:
list
- Any iterable-list of Java Object'slistItemPrinter
-lineWidth
- TheString
that is generated from a list-element and inserted into the top-down output text will be abbreviated / truncated before being appended. The length of the appended string will not exceed the value passed to parameter'lineWidth'
.
NOTE: The pre-pended white-space and the line-number counter is pre-pended to the output text after the maximum-length /'lineWidth'
truncation is performed
ALSO: The value passed must be between 8 and 200, or an exception will throw.indentation
- The number of spaces with which to prefix each line of the returned list. This parameter may be 0 or negative, and when it is no space shall be pre-pended.
IMPORTANT: Each line in the list is also pre-fixed by a counter and a right-parenthesis character'('
The ultimate length of a line when it is inserted into the list is the length of the indentation plus the length the counter-String
plus the final length of the truncated-String
.
The value passed to this parameter must be less or equal to200
, or an exception will throw.seeEscapedNewLinesAsText
- WhenTRUE
is passed to this method, any newlines that are found within theString
-ified list-item will be converted to the two text-characters'\n'
.
WhenFALSE
is passed, as is with all white-space contained by the listed-String's
, sequential white-space characters found in a stringified'list'
element are eliminated and reduced to a single' '
space character.printNulls
- When passedTRUE
, it requests that null objects be included into the output text. The actualString
-literal'null'
is appended into the output when the internal loop encounters a null value in'list'
.
When this parameter is passedFALSE
, if a null value is encountered while iterating'list'
, that null is simply skipped, and nothing is appended to the returned text-String
.
NOTE: When null list-elements are encountered, the counter is always incremented regardless of whether the null is actually printed.showLineNumbers
- When this parameter is passedTRUE
, a line number will appended to the beginning of each line of the output-text. The number is appended after the indentation white-space, and before theString
-ified list item.- Returns:
- a Java-
String
that has a number of lines of text (each ending with a single newline'\n'
character) equal to the number of elements contained by the'Array'
parameter. - See Also:
StringParse.zeroPad10e2(int)
,abbrevEndRDSF(String, int, boolean)
,StringParse.nChars(char, int)
,StringParse.trimLeft(String)
- Code:
- Exact Method Body:
if ((lineWidth < 8) || (lineWidth > 200)) throw new IllegalArgumentException( "[" + lineWidth + "] was passed to parameter 'lineWidth', but this value must be " + "between 8 and 200 is expected" ); if (indentation >= 200) throw new IllegalArgumentException( "[" + indentation + "] was passed to parameter 'indentation', but this value must " + "be 200 or less." ); String indentationStr = (indentation > 0) ? ('\n' + StringParse.nChars(' ', indentation)) : "\n"; StringBuilder sb = new StringBuilder(); int counter = 0; for (ELEM elem : list) { counter++; if ((elem == null) && (! printNulls)) continue; sb.append(indentationStr); if (showLineNumbers) { if (counter < 10) sb.append(StringParse.zeroPad10e2(counter) + ") "); else sb.append(counter + ") "); } if ((elem == null)) sb.append("null"); else sb.append( StringParse.trimLeft( abbrevEndRDSF( listItemPrinter.apply(counter, elem), lineWidth, seeEscapedNewLinesAsText ))); } return sb.toString();
-
printListAbbrev
public static <ELEM> java.lang.String printListAbbrev (ELEM[] arr, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
Convenience Method
Invokes:printListAbbrev(Object[], IntTFunction, int, int, boolean, boolean, boolean)
Passes:Object.toString()
to'listItemPrinter'
- Code:
- Exact Method Body:
return printListAbbrev( arr, (int i, Object o) -> o.toString(), lineWidth, indentation, seeEscapedNewLinesAsText, printNulls, showLineNumbers );
-
printListAbbrev
public static <ELEM> java.lang.String printListAbbrev (ELEM[] list, IntTFunction<? super ELEM,java.lang.String> listItemPrinter, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
Converts any javaArray
into a vertically printed list. This method is very suited to printing out lists of objects whosetoString()
method may return a very long / extendedString
, but whose abbreviation would perfectly suffice for a cursory or circumspect viewing of the list contents.
The "vertically printed" list will contain the results of invoking'listItemPrinter'
on an element of the input'list'
parameter. Afterwards, that resultantString
is abbreviated and trimmed usingabbrevEndRDSF
and alsotrimLeft
so that it fits on a single line of text.
The length of each line in the "Vertically Printed List" will not be longer than'indentation'
(space) characters, plus the value passed to'lineWidth'
.- Parameters:
list
- Any iterable-list of Java Object'slistItemPrinter
-lineWidth
- TheString
that is generated from a list-element and inserted into the top-down output text will be abbreviated / truncated before being appended. The length of the appended string will not exceed the value passed to parameter'lineWidth'
.
NOTE: The pre-pended white-space and the line-number counter is pre-pended to the output text after the maximum-length /'lineWidth'
truncation is performed
ALSO: The value passed must be between 8 and 200, or an exception will throw.indentation
- The number of spaces with which to prefix each line of the returned list. This parameter may be 0 or negative, and when it is no space shall be pre-pended.
IMPORTANT: Each line in the list is also pre-fixed by a counter and a right-parenthesis character'('
The ultimate length of a line when it is inserted into the list is the length of the indentation plus the length the counter-String
plus the final length of the truncated-String
.
The value passed to this parameter must be less or equal to200
, or an exception will throw.seeEscapedNewLinesAsText
- WhenTRUE
is passed to this method, any newlines that are found within theString
-ified list-item will be converted to the two text-characters'\n'
.
WhenFALSE
is passed, as is with all white-space contained by the listed-String's
, sequential white-space characters found in a stringified'list'
element are eliminated and reduced to a single' '
space character.printNulls
- When passedTRUE
, it requests that null objects be included into the output text. The actualString
-literal'null'
is appended into the output when the internal loop encounters a null value in'list'
.
When this parameter is passedFALSE
, if a null value is encountered while iterating'list'
, that null is simply skipped, and nothing is appended to the returned text-String
.
NOTE: When null list-elements are encountered, the counter is always incremented regardless of whether the null is actually printed.showLineNumbers
- When this parameter is passedTRUE
, a line number will appended to the beginning of each line of the output-text. The number is appended after the indentation white-space, and before theString
-ified list item.- Returns:
- a Java-
String
that has a number of lines of text (each ending with a single newline'\n'
character) equal to the number of elements contained by the'Array'
parameter. - See Also:
StringParse.zeroPad10e2(int)
,abbrevEndRDSF(String, int, boolean)
,StringParse.trimLeft(String)
- Code:
- Exact Method Body:
if ((lineWidth < 8) || (lineWidth > 200)) throw new IllegalArgumentException( "[" + lineWidth + "] was passed to parameter 'lineWidth', but this value must be " + "between 8 and 200 is expected" ); if (indentation >= 200) throw new IllegalArgumentException( "[" + indentation + "] was passed to parameter 'indentation', but this value must " + "be 200 or less." ); String indentationStr = (indentation > 0) ? ('\n' + StringParse.nChars(' ', indentation)) : "\n"; StringBuilder sb = new StringBuilder(); int counter = 0; for (ELEM elem : list) { counter++; if ((elem == null) && (! printNulls)) continue; sb.append(indentationStr); if (showLineNumbers) { if (counter < 10) sb.append(StringParse.zeroPad10e2(counter) + ") "); else sb.append(counter + ") "); } if ((elem == null)) sb.append("null"); else sb.append( StringParse.trimLeft( abbrevEndRDSF( listItemPrinter.apply(counter, elem), lineWidth, seeEscapedNewLinesAsText ))); } return sb.toString();
-
lineOrLines
public static java.lang.String lineOrLines(java.lang.String s, int pos, int len, java.lang.String unixColorCode)
This will return the complete text-lines of character data for the line identified by token-substring position parameterspos
andlen
. This method will search, in the left-direction (decreasingString
index) for the first new-line character identified. It will also search, starting at positionpos + len
, for the first new-line character in the right-direction (increasingString
index).
If the token-substring identified bys.substring(pos, len)
itself contains any new-line characters, these will neither affect the prepended, nor the post-pended searchString
. To be precise, any newline characters between'pos'
and'len'
will be irrelevant to the left-wards and right-wards newlines searches for new-line characters.- Parameters:
s
- This may be any valid JavaString
. It ought to be some variant of a text-file. It will be searched for the nearest'\n'
character - in both directions, left and right - from parameterint 'pos'
and parameterint 'len'
pos
- This is a position in the input-parameterString 's'
. The nearest'\n'
(new-line) character, to the left of this position, will be found and identified. If thechar
ats.charAt(pos)
is, itself, a'\n'
(newline) character, then no left-direction search will be performed. The left-most position of the returned substring would then bepos + 1
.len
- The search for the 'right-most''\n'
(newline-character) will begin at position'len'
. If the character ats.charAt(pos + len)
is, itself, a new-line character, then no right-direction search will be performed. The right-most position of the returned substring would bepos + len - 1
.unixColorCode
- If thisString
is null, it will be ignored. If thisString
is non-null, it will be inserted before the "MatchingString
" indicated by the index-boundariespos
TOpos + len
.
NOTE: No Validity Check shall be performed on thisString
, and the user is not obligated to provide aC
valid UNIX Color-CodeString
. Also, a closingC.RESET
is inserted after the terminus of the match.- Returns:
- The
String
demarcated by the first new-line character PLUS 1 BEFORE index'pos'
, and the first new-line character MINUS 1 AFTER indexpos + len
.
NOTE: The above does mean, indeed, that the starting and ending new-lines WILL NOT be included in the returnedString
.
ALSO: Also, if there are no new-line characters before position'pos'
, then every character beginning at position zero will be included in the returnedString
result. Also, if there are no new-line characters after positionpos + len
then every character after positionpos + len
will be appended to the returnedString
result. - Throws:
java.lang.StringIndexOutOfBoundsException
- If either'pos'
, or'pos + len'
are not within the bounds of the inputString 's'
java.lang.IllegalArgumentException
- If the value passed to parameter'len'
is zero or negative.- Code:
- Exact Method Body:
if ((pos >= s.length()) || (pos < 0)) throw new StringIndexOutOfBoundsException( "The integer passed to parameter 'pos' [" + pos + "], is past the bounds of the end " + "of String 's', which has length [" + s.length() + "]" ); if (len <= 0) throw new IllegalArgumentException ("The value passed to parameter 'len' [" + len + "], may not be negative."); if ((pos + len) > s.length()) throw new StringIndexOutOfBoundsException( "The total of parameter 'pos' [" + pos + "], and parameter 'len' [" + len + "], is: " + "[" + (pos + len) + "]. Unfortunately, String parameter 's' only has length " + "[" + s.length() + "]" ); int linesStart, linesEnd, temp; if (pos == 0) linesStart = 0; else if (s.charAt(pos) == '\n') linesStart = pos + 1; else if ((temp = StrIndexOf.left(s, pos, '\n')) != -1) linesStart = temp + 1; else linesStart = 0; if ((pos + len) == s.length()) linesEnd = s.length(); else if (s.charAt(pos + len) == '\n') linesEnd = pos + len; else if ((temp = s.indexOf('\n', pos + len)) != -1) linesEnd = temp; else linesEnd = s.length(); /* // VERY USEFUL FOR DEBUGGING. DO NOT DELETE... // NOTE: This method is the one that GREP uses. System.out.println("s.charAt(pos)\t\t= " + "[" + s.charAt(pos) + "]"); System.out.println("s.charAt(pos+len)\t= " + "[" + s.charAt(pos+len) + "]"); System.out.println("s.length()\t\t= " + s.length()); System.out.println("pos\t\t\t= " + pos); System.out.println("pos + len\t\t= " + (pos + len)); System.out.println("linesStart\t\t= " + linesStart); System.out.println("linesEnd\t\t= " + linesEnd); */ return (unixColorCode != null) ? s.substring(linesStart, pos) + unixColorCode + s.substring(pos, pos + len) + RESET + s.substring(pos + len, linesEnd) : s.substring(linesStart, linesEnd); /* OOPS.... For Posterity, this shall remain, here, but commented s.substring(linesStart, pos) + s.substring(pos, pos + len) + s.substring(pos + len, linesEnd); */
-
line
public static java.lang.String line(java.lang.String s, int pos)
This will return the complete text-line of character data from 'inside' the input-parameterString s
. The meaning of'complete text-line'
, in this method, is that any and all character data between the first'\n'
(new-line character) when scanning towards the right (increasingString
-index) and the first'\n'
character when scanning towards the left (decreasing index) constitutes'a line'
(of text-data).
This scan shall for the left-most and right-most new-line shall begin atString
-index parameterpos
. If either the left-direction or right-direction scan does not find any new-line characters, then start and end indices of the returned line of text shall be demarcated by input-String
index'0'
and indexString.length()
, respectively- Parameters:
s
- This may be any valid JavaString
. It ought to be some variant of a text-file. It will be searched for the nearest'\n'
character - in both directions, left and right - from parameterint 'pos'
.pos
- This is a position in the input-parameterString 's'
. The nearest new-line character both to the left of this position, and to the right, will be found and identified. If the character ats.charAt(pos)
is itself a newline'\n'
character, then an exception shall throw.- Returns:
- The
String
identified by the first new-line character PLUS 1 BEFORE index'pos'
, and the first new-line character MINUS 1 AFTER index'pos + len'
.
NOTE: The above means, that the starting and ending new-lines, themselves, will not be included in theString
that is returned.
ALSO: Also, if there are no new-line characters before position'pos'
, then every character beginning at position zero will be included in the returnedString
result. Also, if there are no new-line characters after position'pos + len'
then every character after position'pos + len'
will be appended to the returnedString
result. - Throws:
java.lang.StringIndexOutOfBoundsException
- If'pos'
is not within the bounds of the inputString 's'
java.lang.IllegalArgumentException
- If the character inString 's'
at position'pos'
is a newline'\n'
, itself.- Code:
- Exact Method Body:
if ((pos > s.length()) || (pos < 0)) throw new StringIndexOutOfBoundsException( "The integer passed to parameter 'pos' [" + pos + "], is past the bounds of the end of " + "String 's', which has length [" + s.length() + "]" ); if (s.charAt(pos) == '\n') throw new IllegalArgumentException( "The position-index for string-parameter 's' contains, itself, a new line character " + "'\\n.' This is not allowed here." ); int lineStart = StrIndexOf.left(s, pos, '\n'); int lineEnd = s.indexOf('\n', pos); if (lineStart == -1) lineStart = 0; if (lineEnd == -1) lineEnd = s.length(); return s.substring(lineStart + 1, lineEnd);
-
firstNLines
public static java.lang.String firstNLines(java.lang.String s, int n)
This will retrieve the first'n'
lines of aString
- where a line is defined as everything up to and including the next newline'\n'
character.- Parameters:
s
- Any javaString
.n
- This is the number of lines of text to retrieve.- Returns:
- a substring of s where the last character in the
String
is a'\n'
. The last character should be the nth'\n'
character found in s. If there is no such character, then the originalString
shall be returned instead. - Throws:
NException
- This exception shall throw if parameter'n'
is less than 1, or longer thans.length()
.- Code:
- Exact Method Body:
NException.check(n, s); int pos = StrIndexOf.nth(s, n, '\n'); if (pos != -1) return s.substring(0, pos + 1); else return s;
-
lastNLines
public static java.lang.String lastNLines(java.lang.String s, int n)
This will retrieve the last 'n' lines of aString
- where a line is defined as everything up to and including the next newline'\n'
character.- Parameters:
s
- Any javaString
.n
- This is the number of lines of text to retrieve.- Returns:
- a substring of
's'
where the last character in theString
is a new-line character'\n'
, and the first character is the character directly before the nth newline'\n'
found in's'
- starting the count at the end of theString
. If there is no such substring, then the originalString
shall be returned. - Throws:
NException
- This exception shall throw if'n'
is less than 1, or longers.length()
.- Code:
- Exact Method Body:
NException.check(n, s); int pos = StrIndexOf.nthFromEnd(s, n, '\n'); if (pos != -1) return s.substring(pos + 1); else return s;
-
trimEachLine
public static java.lang.String trimEachLine(java.lang.String str)
This is used for "trimming each line" of an inputString
. Generally, when dealing with HTML there may be superfluous white-space that is useful in some places, but not necessarily when HTML is copied and pasted to other sections of a page (or to another page, altogether). This will split aString
by new-line characters, and then trim each line, and afterward rebuild theString
and return it.
NOTE: This will only split theString
using the standard'\n'
character. If theString
being used uses'\r'
or'\n\r'
, use a different trim.- Parameters:
str
- This may be anyString
. It will be split by new-line characters'\n'
- Returns:
- Returns the rebuilt
String
, with each line having aString.trim();
operation performed. - Code:
- Exact Method Body:
StringBuilder sb = new StringBuilder(); for (String s : str.split("\\n")) if ((s = s.trim()).length() == 0) continue; else sb.append(s + '\n'); return sb.toString().trim();
-
-