Package Torello.Java
Class StrPrint
- java.lang.Object
-
- Torello.Java.StrPrint
-
public class StrPrint extends java.lang.Object
This class provides severalString
printing utilities such as abbreviation and list printing.
Hi-Lited Source-Code:- View Here: Torello/Java/StrPrint.java
- Open New Browser-Tab: Torello/Java/StrPrint.java
File Size: 43,647 Bytes Line Count: 849 '\n' Characters Found
Stateless Class:This class neither contains any program-state, nor can it be instantiated. The@StaticFunctional
Annotation may also be called 'The Spaghetti Report'.Static-Functional
classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@Stateless
Annotation.
- 1 Constructor(s), 1 declared private, zero-argument constructor
- 19 Method(s), 19 declared static
- 0 Field(s)
-
-
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)
Find Line-Numbers for a Given String-Index Modifier and Type Method static int
lineNumber(String str, int pos)
static int
lineNumberSince(String str, int pos, int prevLineNum, int prevPos)
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)
Abbreviate BOTH Line-Length AND Number-of-Lines Modifier and Type Method static String
widthHeightAbbrev(String s, String horizAbbrevStr, Integer maxLineLength, Integer maxNumLines, boolean compactConsecutiveBlankLines)
-
-
-
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()
Regular Expressions:
This method uses regular-expressions, rather performing an optimized, in-place,String
replacement (such as one with afor
orwhile
loop). This means that there is a little efficiency sacrificed in the name of brevity.
The replacement used in theString.replaceAll
method was thouroughly tested. 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)
-
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)
-
abbrevStart
public static java.lang.String abbrevStart(java.lang.String s, boolean escNewLines, int maxLength)
Convenience Method
Passes:'0'
to parameter'abbrevPos'
, forcing the abbreviation to occur at the start of theString
(if long enough to be abbreviated)- See Also:
abbrev(String, int, boolean, String, int)
- Code:
- Exact Method Body:
return Abbrev.print(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:
return Abbrev.print(s, abbrevPos, escapeNewLines, abbrevStr, maxLength);
-
abbrevEnd
public static java.lang.String abbrevEnd(java.lang.String s, boolean escapeNewLines, int maxLength)
Convenience Method
Parameter:spaceBeforeAbbrev
set toFALSE
Abbreviates: Default ellipsis ('...'
) are placed at the end of theString
- See Also:
abbrev(String, boolean, boolean, String, int)
- Code:
- Exact Method Body:
return Abbrev.print(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:
return Abbrev.print(s, spaceBeforeAbbrev, escapeNewLines, abbrevStr, maxLength);
-
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
Passes:Object.toString()
to'listItemPrinter'
- See Also:
printListAbbrev(Iterable, IntTFunction, int, int, boolean, boolean, boolean)
- Code:
- Exact Method Body:
return PrintListAbbrev.print( 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:
return PrintListAbbrev.print( list, listItemPrinter, lineWidth, indentation, seeEscapedNewLinesAsText, printNulls, showLineNumbers );
-
printListAbbrev
public static <ELEM> java.lang.String printListAbbrev (ELEM[] arr, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, boolean printNulls, boolean showLineNumbers)
Convenience Method
Passes:Object.toString()
to'listItemPrinter'
- See Also:
}
- Code:
- Exact Method Body:
return PrintListAbbrev.print( 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:
return PrintListAbbrev.print( list, listItemPrinter, lineWidth, indentation, seeEscapedNewLinesAsText, printNulls, showLineNumbers );
-
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, lineEnd; // Prevents StrIndexOf from throwing StringINdexOutOfBounds if (pos == 0) lineStart = 0; // Also prevent lineStart equal-to '-1' else if ((lineStart = StrIndexOf.left(s, pos, '\n')) == -1) lineStart = 0; // Prevent lineEnd equal to '-1' if ((lineEnd = s.indexOf('\n', pos)) == -1) lineEnd = s.length(); // if this is the first line, there was no initial '\n', so don't skip it! return (lineStart == 0) // This version returns the String from the position-0 (Pay Attention!) ? s.substring(0, lineEnd) // This version simply eliminates the '\n' that is in the directly-preceeding character : 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.
CRLF Issues:
This will only split theString
using the standard'\n'
character. If theString
being used uses'\r'
or'\n\r'
, use a different trim method.- 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();
-
lineNumber
public static int lineNumber(java.lang.String str, int pos)
Interprets an inputString
as one which was read out of a Text-File. Counts the number of new-line ('\n'
) characters betweenString
indices'0'
and'pos'
This is intended be the Line-Number whereString
-Index parameter'pos'
is located inside the'str'
(presuming'str'
was retrieved from a Text-File).- Parameters:
str
- Any JavaString
, preferably one with multiple lines of text.pos
- Any validString
-Index that occurs ithin'str'
- Returns:
- The Line-Number within Text-File parameter
'str'
which containsString
-Index parameter'pos'
- Throws:
java.lang.StringIndexOutOfBoundsException
- If integer-parameter'pos'
is negative or past the length of theString
-Parameter'str'
.- See Also:
lineNumberSince(String, int, int, int)
- Code:
- Exact Method Body:
if (pos < 0) throw new StringIndexOutOfBoundsException ("The number provided to index parameter 'pos' : [" + pos + "] is negative."); if (pos >= str.length()) throw new StringIndexOutOfBoundsException( "The number provided to index parameter 'pos' : [" + pos + "] is greater than the " + "length of the input String-Parameter 'str' [" + str.length() + "]." ); int lineNum = 1; for (int i=0; i <= pos; i++) if (str.charAt(i) == '\n') lineNum++; return lineNum;
-
lineNumberSince
public static int lineNumberSince(java.lang.String str, int pos, int prevLineNum, int prevPos)
This methe may be used, iteratively, inside of a loop for finding the location of any subsequentString
-Index within a Text-File, based on the information obtained from a previous Line-Number retrieval.
Use inside For-Loop:
This method is designed to be used within a'for'
or'while'
loop. Though it is true that the exception-check which occurs inside this method is superfluous and redundant, the cost incurred by the twoif
-statements is minimal. These checks are used here, in the code, primarily for readability.
If maximum efficiency is needed, then copy and paste the bottom two lines of code into your editor, and use that instead, without the exception-checks.
In the example below, it should be noted how to use both methods to iterate through the line numbers in a Text-File, efficiently.
Example:
int[] posArr = findIndices(myString, "Raindrops on Roses", "Whiskers on Kittens"); int lineNumber = StrPrint.lineNumber(myString, posArr[0]); int prevPos = posArr[0]; System.out.println("There is a match on line: " + lineNumber); for (int i=1; i < posArr.length; i++) { lineNumber = StrPrint.lineNumberSince(myString, posArr[i], lineNumber, prevPos); System.out.println("There is a match on line: " + lineNumber); prevPos = posArr[i]; }
- Parameters:
str
- Any JavaString
. ThisString
will be interpreted as a Text-File whose newline characters ('\n'
chars) represent lines of text.pos
- Any validString
-index within'str'
prevLineNum
- This should be the Line-Number that contains theString
-index'prevPos'
prevPos
- This may be any index contained byString
parameter'str'
. It is expected that this parameter be an index that occured on Line-Number'prevLineNum'
of the Text-File'str'
- Returns:
- The Line-Number within Text-File parameter
'str'
that containsString
-index'pos'
- Throws:
java.lang.IllegalArgumentException
- If'pos'
is less than or equal to'prevPos'
, or if'prevLineNum'
is less than zero.- See Also:
lineNumber(String, int)
- Code:
- Exact Method Body:
if (pos <= prevPos) throw new IllegalArgumentException( "The number provided to index parameter 'pos' : [" + pos + "] is less than or equal " + "to previous-match index-parameter prevPos : [" + prevPos + "]" ); if (prevLineNum < 0) throw new IllegalArgumentException( "You have provided a negative number to Line-Number parameter 'prevLineNum' : " + "[" + prevLineNum + "]" ); for (int i = (prevPos + 1); i <= pos; i++) if (str.charAt(i) == '\n') prevLineNum++; return prevLineNum;
-
widthHeightAbbrev
public static java.lang.String widthHeightAbbrev (java.lang.String s, java.lang.String horizAbbrevStr, java.lang.Integer maxLineLength, java.lang.Integer maxNumLines, boolean compactConsecutiveBlankLines)
This method allows for printing an abbreviation of aString
such that BOTH the number of lines (height), AND the length of each line of text (width) can both be abbreviated. There is even a third abbreviation that is possible, and that is where blank-links can be compacted / flattened first (before the abbreviation process starts).
This method is being used for printing JSON-Response Objects that contain large HTML-PageString's
. Primarily, if you want to see a message, but do not want hundreds or even thousands of lines of HTML blasted across your terminal, then this method is for you!
The packageTorello.Browser's
Web-Sockets Communications is making use of this for printing Chrome-Browser Messages to the terminal.- Parameters:
s
- Any JavaString
horizAbbrevStr
- If you have a specific Abbreviation-String
that you would like to see used in Horizontally-Abbreviated Lines, please pass it here.
Note that this value is directly passed to the'abbrevStr'
parameters in the StandardString
-Abbreviation methods. This means that when this parameter is null, it will be ignored - and if any horizontal (line-length) abbreviattions occur, then the 'Default-AbbreviationString
'"..."
will be used.
Also note that if parameter'maxLineLength'
is passed null, then lines of text will not be shortened. In that case, each line of text will retain its exact length that occured prior to the internalString.split()
invocation.maxLineLength
- If you would like to shorten each line of text which is appended to the returnedString
, then pass a positive value to this parameter.
This parameter may be null, and if it is, it will be ignored. In such cases, individual lines of text will retain their original length.maxNumLines
- This is the maximum number of lines of text that will appear in the returnedString
. Note, under normal operation, if this parameter is passed'3'
, then there will be exactly three lines of text. Furthermore there will be exactly'2'
newline'\n'
characters.compactConsecutiveBlankLines
- When this parameter is passedTRUE
, any series of Empty-Lines, or lines only containing White-Space will be compacted to a single line of text that simply states"[Compacted 10 Blank Lines]"
(or however many White-Space-Only Lines were actually compacted, if that number isn't'10'
)- Returns:
- The modified
String
. - Throws:
java.lang.IllegalArgumentException
- If parameter'maxNumLines'
is less than 3. The returnedString
must be long enough to keep the first line, the last line and the abbreviation note.
This exception will also throw if the internal invocation of the standardString
-abbreviation method is passed a'maxLineLength'
that is less than the minimum line-length requirements for a successful horizontal abbreviation.
Finally, this exception throws if'maxLineLength'
and'maxNumLines'
are both passed null, and'compactConsecutiveBlankLines'
. This scenario is considered an error-case because there it would exact a situation where there is nothing for this method to do.- Code:
- Exact Method Body:
return VertAndHorizAbbrev.print (s, horizAbbrevStr, maxLineLength, maxNumLines, compactConsecutiveBlankLines);
-
-