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: 49,950 Bytes Line Count: 1,095 '\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
- 41 Method(s), 41 declared static
- 3 Field(s), 3 declared static, 3 declared final
-
-
Field Summary
Fields Modifier and Type Field static ReadOnlyList<String>
months
-
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)
Wrap Lines of Text Modifier and Type Method static String
wrap(String s, int lineLen)
static String
wrap(String s, int firstLineLen, int lineLen)
static String
wrapToIndentation(String s, int lineLen)
static String
wrapToIndentation(String s, int firstLineLen, int lineLen)
static String
wrapToIndentationPlus(String s, int firstLineLen, int lineLen, int extraSpaces)
Date & Time Conversion: Convert the Current-Date into a java.lang.String Modifier and Type Method static String
dateStr()
static String
dateStr(char separator)
static String
dateStr(char separator, boolean includeMonthName)
static String
dateStrGOVCN()
Date & Time Conversion: Convert the Current-Time into a java.lang.String Modifier and Type Method static String
timeStr()
static String
timeStr(char separator)
static String
timeStrComplete()
Date & Time Conversion: Convert the Current-Month into a java.lang.String Modifier and Type Method static String
monthStr(int month)
static String
ymDateStr()
static String
ymDateStr(char separator)
static String
ymDateStr(char separator, boolean includeMonthName)
Numeric Strings: Miscellaneous Modifier and Type Method static String
commas(long l)
static String
ordinalIndicator(int i)
Numeric Strings: Convert an Integral-Type to a String, and Pad with Zeros Modifier and Type Method static String
zeroPad(int n)
static String
zeroPad(int n, int powerOf10)
static String
zeroPad10e2(int n)
static String
zeroPad10e4(int n)
-
-
-
Field Detail
-
months
public static final ReadOnlyList<java.lang.String> months
The months of the year, as an immutable list ofString's
.- Code:
- Exact Field Declaration Expression:
public static final ReadOnlyList<String> months = new ReadOnlyArrayList<>( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" );
-
-
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() and AnnotationElem.toString()Regular Expressions: This method uses regular-expressions, rather performing an optimized, in-place,String
replacement (such as one with a'for'
or'while'
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)
- 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
Passes:'0'
to parameter'abbrevPos'
, forcing the abbreviation to occur at the start of theString
(if long enough to be abbreviated)
See Documentation:abbrev(String, int, boolean, String, int)
- Code:
- Exact Method Body:
return Abbrev.print1(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.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'
.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.print1(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 Documentation:abbrev(String, boolean, boolean, String, int)
- Code:
- Exact Method Body:
return Abbrev.print2(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.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'
.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.print2(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 Documentation:printListAbbrev(Iterable, IntTFunction, int, int, boolean, boolean, boolean)
- Code:
- Exact Method Body:
return PrintListAbbrev.print1( 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
- The simple Java Lambda-Function parameter should accept exactly one element of the'list'
and a counter / integer (an integer that relays to the user the location of the current item in the list). The function should return the line of text to be placed in the vertical list.
Any white-space that is included in the returnedString
will be reduced and compacted, and the length of the returned-String
will be abbreviated / truncated before being placed in the return text-String
.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:
zeroPad10e2(int)
,abbrevEndRDSF(String, int, boolean)
,StringParse.nChars(char, int)
,StringParse.trimLeft(String)
- Code:
- Exact Method Body:
return PrintListAbbrev.print1( 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 Documentation:printListAbbrev(Object[], IntTFunction, int, int, boolean, boolean, boolean)
- Code:
- Exact Method Body:
return PrintListAbbrev.print2( 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
- The simple Java Lambda-Function parameter should accept exactly one element of the'list'
and a counter / integer (an integer that relays to the user the location of the current item in the list). The function should return the line of text to be placed in the vertical list.
Any white-space that is included in the returnedString
will be reduced and compacted, and the length of the returned-String
will be abbreviated / truncated before being placed in the return text-String
.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:
zeroPad10e2(int)
,abbrevEndRDSF(String, int, boolean)
,StringParse.trimLeft(String)
- Code:
- Exact Method Body:
return PrintListAbbrev.print2( 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: 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 does mean, indeed, that the starting and ending new-lines WILL NOT be included in the returnedString
.
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'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 two'if'
-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) abbreviations 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'
isFALSE
. This scenario is considered an error-case because there wouldn't be anything for the method to do.- Code:
- Exact Method Body:
return VertAndHorizAbbrev.print (s, horizAbbrevStr, maxLineLength, maxNumLines, compactConsecutiveBlankLines);
-
wrap
public static java.lang.String wrap(java.lang.String s, int lineLen)
Convenience Method
See Documentation:wrap(String, int, int)
Passes same'lineLen'
value to BOTH Line-Length Parameters- Code:
- Exact Method Body:
return Wrap.wrap(s, lineLen, lineLen);
-
wrap
public static java.lang.String wrap(java.lang.String s, int firstLineLen, int lineLen)
Similar to CSS'text-wrap'
property. Inserts new-line characters'n'
into's'
anytime that there are more characters in a row, without any pre-existing Line-Breaks, that are longer than'lineLen'
This method will only break text at points of White-Space. If it is not possible to break a segment of Input-String
Paramter's'
at a White-Space Character without producing a line that is short enough to meet the'lineLen'
specifier, than this method shall break the text in the middle of a word.
This method was primarily developed for printing Error-Messages from the Java-Doc Upgrader's'Messager'
class. Wrapping text inside of a sequence of paragraphs could easily be done using this method too, but the original impetus was for UNIX-Terminal Output.Right Trim: The output results of this method shall contain lines of text which have all been "Right Trimmed" of any and all Space-Characters ('.'
). A paragraph of text, which has already been properly wrapped, and does not need to have any of its lines of text broken shall still undergo a "Right-Trim" operation on each of the lines of text in the paragraph.- Parameters:
s
- Any JavaString
; may not contain'\t', '\f' or '\r'
firstLineLen
- Maximum allowable Line-Length for the first line of text. This feature is particularly useful for to'wrap*...'
the text inside Error-Messages.
When printing'javac'
or'javadoc'
output, for instance, the first line of text is often "appended" to some other, "pre-printed" information that has been derived from else-where in the code.
When this happens, the first line of wrapping needs to be 'wrapped' with a different Maximum-Length than the rest of the wrapped message.lineLen
- The maximum allowable Line-Length for all other lines of text.- Returns:
- Text which has been wrapped, and broken only at white-space locations.
This method will right trim each line of all white-space as it performs this Text-Wrap. Leading White-Space will not be modified.
If a piece of text must be wrapped, but was too long to be broken at a Space-Demarcated Word-Boundary, then that text will be broken at the first character of data that has overrun the specified Line-Length requirement. - Throws:
StringFormatException
- If there are any'n', 't'
or'r'
characters found within the Input-String, then this exception throws.
Note that this requirement is strict, and cannot be changed. Due to the overly complicated nature of what a tab-character can sometimes represent, this variant of'wrap'
strictly requires that all three of these difficult-to-manage characters be eliminated from the input.
If any of these three are present, then this exception shall throw.java.lang.IllegalArgumentException
- If'firstLineLen'
or'lineLen'
are zero or negative.- Code:
- Exact Method Body:
return Wrap.wrap(s, firstLineLen, lineLen);
-
wrapToIndentation
public static java.lang.String wrapToIndentation(java.lang.String s, int lineLen)
Convenience Method
See Documentation:wrapToIndentation(String, int, int)
Passes same'lineLen'
value to BOTH Line-Length Parameters- Code:
- Exact Method Body:
return WrapToIndentation.wrap(s, lineLen, lineLen);
-
wrapToIndentation
public static java.lang.String wrapToIndentation(java.lang.String s, int firstLineLen, int lineLen)
Similar to CSS'text-wrap'
property. Inserts new-line characters'n'
into's'
anytime that there are more characters in a row, without any pre-existing Line-Breaks, that are longer than'lineLen'
This method will only break text at points of White-Space. If it is not possible to break a segment of Input-String
Paramter's'
at a White-Space Character without producing a line that is short enough to meet the'lineLen'
specifier, than this method shall break the text in the middle of a word.
This method was primarily developed for printing Error-Messages from the Java-Doc Upgrader's'Messager'
class. Wrapping text inside of a sequence of paragraphs could easily be done using this method too, but the original impetus was for UNIX-Terminal Output.Right Trim: The output results of this method shall contain lines of text which have all been "Right Trimmed" of any and all Space-Characters ('.'
). A paragraph of text, which has already been properly wrapped, and does not need to have any of its lines of text broken shall still undergo a "Right-Trim" operation on each of the lines of text in the paragraph.
Wrap to Indentation:
The output of this method is highly similar to that produced by the standard'wrap'
method (directly above this method, in this class). It may be of some importance to note that these were developed with the goal of supporting the Java-Doc Upgrader class with a proper Error-Message Printing-Class.
As such, when an Error-Message is output, it will often contain lines of text which have been indented in order to make the (sometimes very complex) details about an error more readable and intelligible. When a line of text for an Error-Message overruns past the specified Line-Length provided (as a parameter to this method), the line is broken, and wrapped to the amount of Space-Indentation contained by the whatever indentation is contained within the previous line of text.
Another way of saying this is that whenever a Line-Wrap occurs, the line that is broken and wrapped "inherits" the amount of indentation present in the line directly above it. Included, below, is a sample use of this method. The input text is the "Error-Message" that is intended to be printed by theMessager
class of any Software-Processing Application (such as the Java-Doc Upgrader).
Example:
final String fDir = "/home/MyCloudLoginID/My/Very/Long/Directory/Name/"; final String fName = fDir + "MyLongFileName.txt"; try { String fileAsStr = FileRW.loadFileToString(fName); } catch (IOException ioe) { // This invocation uses "StrPrint.wrapToIndentation" to print this message Messager.userErrorContinue( "The following, User-Provided, file could not be loaded from disk:\n" + " " + BYELLOW + fName + RESET, ioe ); return false; }
the above'.java'
source would print the following to a Terminal-Window. Please note that due to the length of the file-name, the line of text where it is printed is "wrapped". The wrapping that occursThe following, User-Provided, file could not be loaded from disk: /home/MyCloudLoginID/My/Very/Long/Directory/Name/ MyLongFileName.txt- Parameters:
s
- Any JavaString
; may not contain'\t', '\f' or '\r'
firstLineLen
- Maximum allowable Line-Length for the first line of text. This feature is particularly useful for to'wrap*...'
the text inside Error-Messages.
When printing'javac'
or'javadoc'
output, for instance, the first line of text is often "appended" to some other, "pre-printed" information that has been derived from else-where in the code.
When this happens, the first line of wrapping needs to be 'wrapped' with a different Maximum-Length than the rest of the wrapped message.lineLen
- The maximum allowable Line-Length for all other lines of text.- Returns:
- Text which has been wrapped, and broken only at white-space locations.
This method will right trim each line of all white-space as it performs this Text-Wrap. Leading White-Space will not be modified.
If a piece of text must be wrapped, but was too long to be broken at a Space-Demarcated Word-Boundary, then that text will be broken at the first character of data that has overrun the specified Line-Length requirement.
As already explained, the returnedString
shall contain "wrapped" text which has an amount of indentation (space characters) equal to whatever line is directly above it. Indented lines, effectively, "inherit" the amount of indentation present in the line coming directly before them. - Throws:
StringFormatException
- If there are any'n', 't'
or'r'
characters found within the Input-String, then this exception throws.
Note that this requirement is strict, and cannot be changed. Due to the overly complicated nature of what a tab-character can sometimes represent, this variant of'wrap'
strictly requires that all three of these difficult-to-manage characters be eliminated from the input.
If any of these three are present, then this exception shall throw.java.lang.IllegalArgumentException
- If'firstLineLen'
or'lineLen'
are zero or negative.- Code:
- Exact Method Body:
return WrapToIndentation.wrap(s, firstLineLen, lineLen);
-
wrapToIndentationPlus
public static java.lang.String wrapToIndentationPlus(java.lang.String s, int firstLineLen, int lineLen, int extraSpaces)
Similar to CSS'text-wrap'
property. Inserts new-line characters'n'
into's'
anytime that there are more characters in a row, without any pre-existing Line-Breaks, that are longer than'lineLen'
This method will only break text at points of White-Space. If it is not possible to break a segment of Input-String
Paramter's'
at a White-Space Character without producing a line that is short enough to meet the'lineLen'
specifier, than this method shall break the text in the middle of a word.
This method was primarily developed for printing Error-Messages from the Java-Doc Upgrader's'Messager'
class. Wrapping text inside of a sequence of paragraphs could easily be done using this method too, but the original impetus was for UNIX-Terminal Output.Right Trim: The output results of this method shall contain lines of text which have all been "Right Trimmed" of any and all Space-Characters ('.'
). A paragraph of text, which has already been properly wrapped, and does not need to have any of its lines of text broken shall still undergo a "Right-Trim" operation on each of the lines of text in the paragraph.- Parameters:
s
- Any JavaString
; may not contain'\t', '\f' or '\r'
firstLineLen
- Maximum allowable Line-Length for the first line of text. This feature is particularly useful for to'wrap*...'
the text inside Error-Messages.
When printing'javac'
or'javadoc'
output, for instance, the first line of text is often "appended" to some other, "pre-printed" information that has been derived from else-where in the code.
When this happens, the first line of wrapping needs to be 'wrapped' with a different Maximum-Length than the rest of the wrapped message.lineLen
- The maximum allowable Line-Length for all other lines of text.extraSpaces
- Wrapped text will get an additional amount of indentation, past any and all inherited indentation- Returns:
- Wrapped.
- Throws:
StringFormatException
- If there are any'n', 't'
or'r'
characters found within the Input-String, then this exception throws.
Note that this requirement is strict, and cannot be changed. Due to the overly complicated nature of what a tab-character can sometimes represent, this variant of'wrap'
strictly requires that all three of these difficult-to-manage characters be eliminated from the input.
If any of these three are present, then this exception shall throw.java.lang.IllegalArgumentException
- If'firstLineLen'
or'lineLen'
are zero or negative.- Code:
- Exact Method Body:
return WrapToIndentationPlus.wrap(s, firstLineLen, lineLen, extraSpaces);
-
dateStr
public static java.lang.String dateStr()
Generates a "Date String" using the character separator'.'
- Returns:
- A
String
in the form:YYYY.MM.DD
- Code:
- Exact Method Body:
return dateStr('.', false);
-
dateStr
public static java.lang.String dateStr(char separator)
Generates a "Date String" using the separator parameter as the separator between numbers- Parameters:
separator
- Any ASCII or UniCode character.- Returns:
- A
String
of the form:YYYYcMMcDD
where'c'
is the passed'separator'
parameter. - Code:
- Exact Method Body:
return dateStr(separator, false);
-
dateStrGOVCN
public static java.lang.String dateStrGOVCN()
Generates a "Date String" that is consistent with the directory-name file-storage locations used to store articles fromhttp://Gov.CN
.- Returns:
- The
String's
used for the Chinese Government Web-Portal Translation Pages - Code:
- Exact Method Body:
return dateStr('/', false).replaceFirst("/", "-");
-
dateStr
public static java.lang.String dateStr(char separator, boolean includeMonthName)
This class is primary included because although Java has a pretty reasonable "general purpose" calendar class/interface, but a consistent / sameString
since is needed because the primary use here is for building the names of files.- Parameters:
separator
- Any ASCII or Uni-Code character.includeMonthName
- When TRUE, the English-Name of the month ('January'
...'December'
) will be appended to the month number in the returnedString
.- Returns:
- The year, month, and day as a
String
. - Code:
- Exact Method Body:
Calendar c = internalCalendar; String m = zeroPad10e2(c.get(Calendar.MONTH) + 1); // January is month zero! String d = zeroPad10e2(c.get(Calendar.DAY_OF_MONTH)); if (includeMonthName) m += " - " + c.getDisplayName(Calendar.MONTH, 2, Locale.US); return (separator != 0) ? (c.get(Calendar.YEAR) + "" + separator + m + separator + d) : (c.get(Calendar.YEAR) + "" + m + d);
-
monthStr
-
ymDateStr
public static java.lang.String ymDateStr()
Returns aString
that has the year and the month (but not the day, or any other time related components).- Returns:
- Returns the current year and month as a
String
. - Code:
- Exact Method Body:
return ymDateStr('.', false);
-
ymDateStr
public static java.lang.String ymDateStr(char separator)
Returns aString
that has the year and the month (but not the day, or other time components).- Parameters:
separator
- The single-character separator used between year, month and day.- Returns:
- The current year and month as a
String
. - Code:
- Exact Method Body:
return ymDateStr(separator, false);
-
ymDateStr
public static java.lang.String ymDateStr(char separator, boolean includeMonthName)
Returns aString
that has the year and the month (but not the day, or other time components).- Parameters:
separator
- The single-character separator used between year, month and day.includeMonthName
- When this is true, the name of the month, in English, is included with the returnString
.- Returns:
YYYY<separator>MM(? include-month-name)
- Code:
- Exact Method Body:
Calendar c = internalCalendar; String m = zeroPad10e2(c.get(Calendar.MONTH) + 1); // January is month zero! if (includeMonthName) m += " - " + c.getDisplayName(Calendar.MONTH, 2, Locale.US); return (separator != 0) ? (c.get(Calendar.YEAR) + "" + separator + m) : (c.get(Calendar.YEAR) + "" + m);
-
timeStr
public static java.lang.String timeStr()
Returns the current time as aString
.- Returns:
- military time - with AM|PM (redundant) added too.
Includes only Hour and Minute - separated by a colon character
':'
- See Also:
timeStr(char)
- Code:
- Exact Method Body:
return timeStr(':');
-
timeStr
public static java.lang.String timeStr(char separator)
Returns the current time as aString
.- Parameters:
separator
- The character used to separate the minute & hour fields- Returns:
- military time - with AM|PM added redundantly, and a separator of your choosing.
- Code:
- Exact Method Body:
Calendar c = internalCalendar; int ht = c.get(Calendar.HOUR) + ((c.get(Calendar.AM_PM) == Calendar.AM) ? 0 : 12); String h = zeroPad10e2((ht == 0) ? 12 : ht); // 12:00 is represented as "0"... changes this... String m = zeroPad10e2(c.get(Calendar.MINUTE)); String p = (c.get(Calendar.AM_PM) == Calendar.AM) ? "AM" : "PM"; return (separator != 0) ? (h + separator + m + separator + p) : (h + m + p);
-
timeStrComplete
public static java.lang.String timeStrComplete()
Returns the current time as aString
. This method uses all time components available.- Returns:
- military time - with AM|PM added redundantly.
- Code:
- Exact Method Body:
Calendar c = internalCalendar; int ht = c.get(Calendar.HOUR) + ((c.get(Calendar.AM_PM) == Calendar.AM) ? 0 : 12); String h = zeroPad10e2((ht == 0) ? 12 : ht); // 12:00 is represented as "0" String m = zeroPad10e2(c.get(Calendar.MINUTE)); String s = zeroPad10e2(c.get(Calendar.SECOND)); String ms = zeroPad(c.get(Calendar.MILLISECOND)); String p = (c.get(Calendar.AM_PM) == Calendar.AM) ? "AM" : "PM"; return h + '-' + m + '-' + p + '-' + s + '-' + ms + "ms";
-
commas
public static java.lang.String commas(long l)
Makes along
number like123456789
into a number-string such as:"123,456,789"
. Java'spackage java.text.*
is easy to use, and versatile, but the commands are not always so easy to remember.- Parameters:
l
- Anylong
integer. Comma's will be inserted for every third power of ten- Returns:
- After calling java's
java.text.DecimalFormat
class, aString
representing this parameter will be returned. - Code:
- Exact Method Body:
return formatter.format(l);
-
ordinalIndicator
public static java.lang.String ordinalIndicator(int i)
The words "ordinal indicator" are referring to the little characterString
that is often used in English to make a number seem more a part of an english sentence.- Parameters:
i
- Any positive integer (greater than 0)- Returns:
- This will return the following strings:
Input: RETURNS: i = 1 "st" (as in "1st","first") i = 2 "nd" (as in "2nd", "second") i = 4 "th" (as in "4th") i = 23 "rd" (as in "23rd") - Throws:
java.lang.IllegalArgumentException
- If i is negative, or zero- Code:
- Exact Method Body:
if (i < 1) throw new IllegalArgumentException ("i: " + i + "\tshould be a natural number > 0."); // Returns the last 2 digits of the number, or the number itself if it is less than 100. // Any number greater than 100 - will not have the "text-ending" (1st, 2nd, 3rd..) affected // by the digits after the first two digits. Just analyze the two least-significant digits i = i % 100; // All numbers between "4th" and "19th" end with "th" if ((i > 3) && (i < 20)) return "th"; // set i to be the least-significant digit of the number - if that number was 1, 2, or 3 i = i % 10; // Obvious: English Rules. if (i == 1) return "st"; if (i == 2) return "nd"; if (i == 3) return "rd"; // Compiler is complaining. This statement should never be executed. return "th";
-
zeroPad
public static java.lang.String zeroPad(int n)
This just zero-pads integers with "prepended" zero's. java.text has all kinds of extremely intricate zero-padding and text-formatting classes. However, here, these are generally used for debug, line-number, or count information that is printed to the UNIX terminal. When this is the case, a simple and easily remembered 'one line method' is a lot more useful than all of the highly-scalable versions of the text-formatting classes in java.text.- Parameters:
n
- Any Integer. If'n'
is negative or greater than 1,000 - null is returned.- Returns:
- A zero-padded
String
- to precisely three orders of 10, as in the example table below:Input RETURNS: n = 9 "009" n = 99 "099" n = 999 "999" n = 9999 null n = -10 null - See Also:
zeroPad10e2(int)
,zeroPad10e4(int)
- Code:
- Exact Method Body:
if (n < 0) return null; if (n < 10) return "00" + n; if (n < 100) return "0" + n; if (n < 1000) return "" + n; return null;
-
zeroPad10e2
public static java.lang.String zeroPad10e2(int n)
Pads an integer such that it contains enough leading zero's to ensure aString
-length of two.- Parameters:
n
- Must be an integer between 0 and 99, or else null will be returned- Returns:
- A zero-padded String of the integer, to precisely two orders of 10
Null is returned if the number cannot fit within two spaces.
Example table follows:Input RETURNS: n = 9 "09" n = 99 "99" n = 999 null n = -10 null - See Also:
zeroPad(int)
- Code:
- Exact Method Body:
if (n < 0) return null; if (n < 10) return "0" + n; if (n < 100) return "" + n; return null;
-
zeroPad10e4
public static java.lang.String zeroPad10e4(int n)
Pads an integer such that it contains enough leading zero's to ensure a String-length of four.- Parameters:
n
- Must be an integer between 0 and 9999, or else null will be returned- Returns:
- A zero-padded String of the integer, to precisely four orders of 10.
Null is returned if the number cannot fit within four spaces.
Example table follows:Input RETURNS: n = 9 "0009" n = 99 "0099" n = 999 "0999" n = 9999 "9999" n = 99999 null n = -10 null - See Also:
zeroPad(int)
- Code:
- Exact Method Body:
if (n < 0) return null; if (n < 10) return "000" + n; if (n < 100) return "00" + n; if (n < 1000) return "0" + n; if (n < 10000) return "" + n; return null;
-
zeroPad
public static java.lang.String zeroPad(int n, int powerOf10)
Pad's an integer with leading zeroes into aString
. The number of zeroes padded is equal to parameter'powerOf10'
. Ifint 'powerOf10'
were equal to zero, then any integer passed to this function would return aString
that was precisely three characters long. If the value of parameterint 'n'
were larger than1,000
or negative, then null would be returned.- Parameters:
n
- Must be an integer between'0'
and'9999'
where the number of'9'
digits is equal to the value of parameterint 'powerOf10'
powerOf10
- This must be a positive integer greater than'1'
. It may not be larger'11'
. The largest value that any integer in Java may attain is'2,147,483, 647'
- Returns:
- A zero padded
String
. If a negative number is passed to parameter'n'
, then 'null' shall be returned. Null shall also be returned if the "Power of 10 Exponent of parametern
" is greater than the integer-value of parameter'powerOf10'
For Instance: a call to:zeroPad(54321, 4);
would return null since the value of parameter'n'
has five-decimal-places, but'powerOf10'
is only 4! - Throws:
java.lang.IllegalArgumentException
- if the value parameter'powerOf10'
is less than 2, or greater than11
.- Code:
- Exact Method Body:
if (n < 0) return null; // Negative Values of 'n' not allowed char[] cArr = new char[powerOf10]; // The String's length will be equal to 'powerOf10' String s = "" + n; // (or else 'null' would be returned) int i = powerOf10 - 1; // Internal Loop variable int j = s.length() - 1; // Internal Loop variable Arrays.fill(cArr, '0'); // Initially, fill the output char-array with all // zeros while ((i >= 0) && (j >= 0)) // Now start filling that char array with the cArr[i--] = s.charAt(j--); // actual number if (j >= 0) return null; // if all of parameter 'n' was inserted into the // output (number 'n' didn't fit) then powerOf10 // was insufficient, so return null. return new String(cArr);
-
-