You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2021/07/24 15:20:31 UTC

[commons-text] branch master updated (62f48e5 -> 04a7952)

This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git.


    from 62f48e5  Javadoc: Close HTML tags.
     new 2ff16ee  Sort members.
     new d1fde0d  Sort members.
     new 04748ac  Sort members.
     new 04a7952  Sort members.

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../org/apache/commons/text/AlphabetConverter.java |  614 +++++-----
 .../java/org/apache/commons/text/CaseUtils.java    |   22 +-
 .../org/apache/commons/text/CompositeFormat.java   |   28 +-
 .../apache/commons/text/ExtendedMessageFormat.java |  390 +++---
 .../org/apache/commons/text/FormattableUtils.java  |   80 +-
 .../apache/commons/text/RandomStringGenerator.java |  494 ++++----
 .../java/org/apache/commons/text/StrLookup.java    |  140 +--
 .../java/org/apache/commons/text/StrMatcher.java   |  488 ++++----
 .../org/apache/commons/text/StrSubstitutor.java    | 1034 ++++++++--------
 .../org/apache/commons/text/StringEscapeUtils.java |  630 +++++-----
 .../java/org/apache/commons/text/WordUtils.java    | 1290 ++++++++++----------
 .../apache/commons/text/diff/CommandVisitor.java   |   14 +-
 .../org/apache/commons/text/diff/EditCommand.java  |   18 +-
 .../org/apache/commons/text/diff/EditScript.java   |   42 +-
 .../commons/text/diff/ReplacementsFinder.java      |   20 +-
 .../commons/text/diff/StringsComparator.java       |  180 +--
 .../apache/commons/text/numbers/DoubleFormat.java  |  722 +++++------
 .../apache/commons/text/numbers/ParsedDecimal.java |  854 ++++++-------
 .../text/translate/CharSequenceTranslator.java     |   42 +-
 .../commons/text/translate/CsvTranslators.java     |   32 +-
 .../text/translate/NumericEntityEscaper.java       |   66 +-
 .../text/translate/NumericEntityUnescaper.java     |    8 +-
 .../commons/text/translate/OctalUnescaper.java     |   40 +-
 .../text/translate/SinglePassTranslator.java       |   20 +-
 .../commons/text/translate/UnicodeEscaper.java     |   96 +-
 25 files changed, 3682 insertions(+), 3682 deletions(-)

[commons-text] 03/04: Sort members.

Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git

commit 04748ac3693163685e411167e5c689eb9ae98dac
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Jul 24 11:18:38 2021 -0400

    Sort members.
---
 .../org/apache/commons/text/AlphabetConverter.java |  614 +++++-----
 .../java/org/apache/commons/text/CaseUtils.java    |   22 +-
 .../org/apache/commons/text/CompositeFormat.java   |   28 +-
 .../apache/commons/text/ExtendedMessageFormat.java |  390 +++---
 .../org/apache/commons/text/FormattableUtils.java  |   80 +-
 .../apache/commons/text/RandomStringGenerator.java |  494 ++++----
 .../java/org/apache/commons/text/StrLookup.java    |  140 +--
 .../java/org/apache/commons/text/StrMatcher.java   |  488 ++++----
 .../org/apache/commons/text/StrSubstitutor.java    | 1034 ++++++++--------
 .../org/apache/commons/text/StringEscapeUtils.java |  630 +++++-----
 .../java/org/apache/commons/text/WordUtils.java    | 1290 ++++++++++----------
 11 files changed, 2605 insertions(+), 2605 deletions(-)

diff --git a/src/main/java/org/apache/commons/text/AlphabetConverter.java b/src/main/java/org/apache/commons/text/AlphabetConverter.java
index 1229732..58f0649 100644
--- a/src/main/java/org/apache/commons/text/AlphabetConverter.java
+++ b/src/main/java/org/apache/commons/text/AlphabetConverter.java
@@ -76,6 +76,218 @@ import org.apache.commons.lang3.StringUtils;
 public final class AlphabetConverter {
 
     /**
+     * Arrow constant, used for converting the object into a string.
+     */
+    private static final String ARROW = " -> ";
+
+    /**
+     * Creates new String that contains just the given code point.
+     *
+     * @param i code point
+     * @return a new string with the new code point
+     * @see "http://www.oracle.com/us/technologies/java/supplementary-142654.html"
+     */
+    private static String codePointToString(final int i) {
+        if (Character.charCount(i) == 1) {
+            return String.valueOf((char) i);
+        }
+        return new String(Character.toChars(i));
+    }
+
+    /**
+     * Converts characters to integers.
+     *
+     * @param chars array of characters
+     * @return an equivalent array of integers
+     */
+    private static Integer[] convertCharsToIntegers(final Character[] chars) {
+        if (ArrayUtils.isEmpty(chars)) {
+            return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;
+        }
+        final Integer[] integers = new Integer[chars.length];
+        for (int i = 0; i < chars.length; i++) {
+            integers[i] = (int) chars[i];
+        }
+        return integers;
+    }
+
+    /**
+     * Creates an alphabet converter, for converting from the original alphabet,
+     * to the encoded alphabet, while leaving
+     * the characters in <em>doNotEncode</em> as they are (if possible).
+     *
+     * <p>Duplicate letters in either original or encoding will be ignored.</p>
+     *
+     * @param original an array of ints representing the original alphabet in
+     *                 codepoints
+     * @param encoding an array of ints representing the alphabet to be used for
+     *                 encoding, in codepoints
+     * @param doNotEncode an array of ints representing the chars to be encoded
+     *                    using the original alphabet - every char
+     *                    here must appear in both the previous params
+     * @return The AlphabetConverter
+     * @throws IllegalArgumentException if an AlphabetConverter cannot be
+     *                                   constructed
+     */
+    public static AlphabetConverter createConverter(
+            final Integer[] original,
+            final Integer[] encoding,
+            final Integer[] doNotEncode) {
+        final Set<Integer> originalCopy = new LinkedHashSet<>(Arrays.asList(original));
+        final Set<Integer> encodingCopy = new LinkedHashSet<>(Arrays.asList(encoding));
+        final Set<Integer> doNotEncodeCopy = new LinkedHashSet<>(Arrays.asList(doNotEncode));
+
+        final Map<Integer, String> originalToEncoded = new LinkedHashMap<>();
+        final Map<String, String> encodedToOriginal = new LinkedHashMap<>();
+        final Map<Integer, String> doNotEncodeMap = new HashMap<>();
+
+        final int encodedLetterLength;
+
+        for (final int i : doNotEncodeCopy) {
+            if (!originalCopy.contains(i)) {
+                throw new IllegalArgumentException(
+                        "Can not use 'do not encode' list because original "
+                                + "alphabet does not contain '"
+                                + codePointToString(i) + "'");
+            }
+
+            if (!encodingCopy.contains(i)) {
+                throw new IllegalArgumentException(
+                        "Can not use 'do not encode' list because encoding alphabet does not contain '"
+                                + codePointToString(i) + "'");
+            }
+
+            doNotEncodeMap.put(i, codePointToString(i));
+        }
+
+        if (encodingCopy.size() >= originalCopy.size()) {
+            encodedLetterLength = 1;
+
+            final Iterator<Integer> it = encodingCopy.iterator();
+
+            for (final int originalLetter : originalCopy) {
+                final String originalLetterAsString =
+                        codePointToString(originalLetter);
+
+                if (doNotEncodeMap.containsKey(originalLetter)) {
+                    originalToEncoded.put(originalLetter,
+                            originalLetterAsString);
+                    encodedToOriginal.put(originalLetterAsString,
+                            originalLetterAsString);
+                } else {
+                    Integer next = it.next();
+
+                    while (doNotEncodeCopy.contains(next)) {
+                        next = it.next();
+                    }
+
+                    final String encodedLetter = codePointToString(next);
+
+                    originalToEncoded.put(originalLetter, encodedLetter);
+                    encodedToOriginal.put(encodedLetter,
+                            originalLetterAsString);
+                }
+            }
+
+            return new AlphabetConverter(originalToEncoded,
+                    encodedToOriginal,
+                    encodedLetterLength);
+
+        }
+        if (encodingCopy.size() - doNotEncodeCopy.size() < 2) {
+            throw new IllegalArgumentException(
+                    "Must have at least two encoding characters (excluding "
+                            + "those in the 'do not encode' list), but has "
+                            + (encodingCopy.size() - doNotEncodeCopy.size()));
+        }
+        // we start with one which is our minimum, and because we do the
+        // first division outside the loop
+        int lettersSoFar = 1;
+
+        // the first division takes into account that the doNotEncode
+        // letters can't be in the leftmost place
+        int lettersLeft = (originalCopy.size() - doNotEncodeCopy.size())
+                / (encodingCopy.size() - doNotEncodeCopy.size());
+
+        while (lettersLeft / encodingCopy.size() >= 1) {
+            lettersLeft = lettersLeft / encodingCopy.size();
+            lettersSoFar++;
+        }
+
+        encodedLetterLength = lettersSoFar + 1;
+
+        final AlphabetConverter ac =
+                new AlphabetConverter(originalToEncoded,
+                        encodedToOriginal,
+                        encodedLetterLength);
+
+        ac.addSingleEncoding(encodedLetterLength,
+                StringUtils.EMPTY,
+                encodingCopy,
+                originalCopy.iterator(),
+                doNotEncodeMap);
+
+        return ac;
+    }
+
+    /**
+     * Creates an alphabet converter, for converting from the original alphabet,
+     * to the encoded alphabet, while leaving the characters in
+     * <em>doNotEncode</em> as they are (if possible).
+     *
+     * <p>Duplicate letters in either original or encoding will be ignored.</p>
+     *
+     * @param original an array of chars representing the original alphabet
+     * @param encoding an array of chars representing the alphabet to be used
+     *                 for encoding
+     * @param doNotEncode an array of chars to be encoded using the original
+     *                    alphabet - every char here must appear in
+     *                    both the previous params
+     * @return The AlphabetConverter
+     * @throws IllegalArgumentException if an AlphabetConverter cannot be
+     *                                  constructed
+     */
+    public static AlphabetConverter createConverterFromChars(
+            final Character[] original,
+            final Character[] encoding,
+            final Character[] doNotEncode) {
+        return AlphabetConverter.createConverter(
+                convertCharsToIntegers(original),
+                convertCharsToIntegers(encoding),
+                convertCharsToIntegers(doNotEncode));
+    }
+
+    /**
+     * Creates a new converter from a map.
+     *
+     * @param originalToEncoded a map returned from getOriginalToEncoded()
+     * @return The reconstructed AlphabetConverter
+     * @see AlphabetConverter#getOriginalToEncoded()
+     */
+    public static AlphabetConverter createConverterFromMap(
+            final Map<Integer, String> originalToEncoded) {
+        final Map<Integer, String> unmodifiableOriginalToEncoded =
+                Collections.unmodifiableMap(originalToEncoded);
+        final Map<String, String> encodedToOriginal = new LinkedHashMap<>();
+
+        int encodedLetterLength = 1;
+
+        for (final Entry<Integer, String> e
+                : unmodifiableOriginalToEncoded.entrySet()) {
+            final String originalAsString = codePointToString(e.getKey());
+            encodedToOriginal.put(e.getValue(), originalAsString);
+
+            if (e.getValue().length() > encodedLetterLength) {
+                encodedLetterLength = e.getValue().length();
+            }
+        }
+
+        return new AlphabetConverter(unmodifiableOriginalToEncoded,
+                encodedToOriginal,
+                encodedLetterLength);
+    }
+
+    /**
      * Original string to be encoded.
      */
     private final Map<Integer, String> originalToEncoded;
@@ -91,11 +303,6 @@ public final class AlphabetConverter {
     private final int encodedLetterLength;
 
     /**
-     * Arrow constant, used for converting the object into a string.
-     */
-    private static final String ARROW = " -> ";
-
-    /**
      * Hidden constructor for alphabet converter. Used by static helper methods.
      *
      * @param originalToEncoded original string to be encoded
@@ -112,41 +319,61 @@ public final class AlphabetConverter {
     }
 
     /**
-     * Encodes a given string.
+     * Recursive method used when creating encoder/decoder.
      *
-     * @param original the string to be encoded
-     * @return The encoded string, {@code null} if the given string is null
-     * @throws UnsupportedEncodingException if chars that are not supported are
-     *                                      encountered
+     * @param level at which point it should add a single encoding
+     * @param currentEncoding current encoding
+     * @param encoding letters encoding
+     * @param originals original values
+     * @param doNotEncodeMap map of values that should not be encoded
      */
-    public String encode(final String original)
-            throws UnsupportedEncodingException {
-        if (original == null) {
-            return null;
-        }
+    @SuppressWarnings("PMD")
+    private void addSingleEncoding(final int level,
+                                   final String currentEncoding,
+                                   final Collection<Integer> encoding,
+                                   final Iterator<Integer> originals,
+                                   final Map<Integer, String> doNotEncodeMap) {
 
-        final StringBuilder sb = new StringBuilder();
+        if (level > 0) {
+            for (final int encodingLetter : encoding) {
+                if (!originals.hasNext()) {
+                    return; // done encoding all the original alphabet
+                }
+                // this skips the doNotEncode chars if they are in the
+                // leftmost place
+                if (level != encodedLetterLength
+                        || !doNotEncodeMap.containsKey(encodingLetter)) {
+                    addSingleEncoding(level - 1,
+                            currentEncoding
+                                    + codePointToString(encodingLetter),
+                            encoding,
+                            originals,
+                            doNotEncodeMap
+                    );
+                }
+            }
+        } else {
+            Integer next = originals.next();
 
-        for (int i = 0; i < original.length();) {
-            final int codepoint = original.codePointAt(i);
+            while (doNotEncodeMap.containsKey(next)) {
+                final String originalLetterAsString = codePointToString(next);
 
-            final String nextLetter = originalToEncoded.get(codepoint);
+                originalToEncoded.put(next, originalLetterAsString);
+                encodedToOriginal.put(originalLetterAsString,
+                        originalLetterAsString);
 
-            if (nextLetter == null) {
-                throw new UnsupportedEncodingException(
-                        "Couldn't find encoding for '"
-                                + codePointToString(codepoint)
-                                + "' in "
-                                + original
-                );
+                if (!originals.hasNext()) {
+                    return;
+                }
+
+                next = originals.next();
             }
 
-            sb.append(nextLetter);
+            final String originalLetterAsString = codePointToString(next);
 
-            i += Character.charCount(codepoint);
+            originalToEncoded.put(next, currentEncoding);
+            encodedToOriginal.put(currentEncoding, originalLetterAsString);
         }
-
-        return sb.toString();
     }
 
     /**
@@ -196,94 +423,38 @@ public final class AlphabetConverter {
     }
 
     /**
-     * Gets the length of characters in the encoded alphabet that are necessary
-     * for each character in the original
-     * alphabet.
-     *
-     * @return The length of the encoded char
-     */
-    public int getEncodedCharLength() {
-        return encodedLetterLength;
-    }
-
-    /**
-     * Gets the mapping from integer code point of source language to encoded
-     * string. Use to reconstruct converter from
-     * serialized map.
-     *
-     * @return The original map
-     */
-    public Map<Integer, String> getOriginalToEncoded() {
-        return Collections.unmodifiableMap(originalToEncoded);
-    }
-
-    /**
-     * Recursive method used when creating encoder/decoder.
+     * Encodes a given string.
      *
-     * @param level at which point it should add a single encoding
-     * @param currentEncoding current encoding
-     * @param encoding letters encoding
-     * @param originals original values
-     * @param doNotEncodeMap map of values that should not be encoded
+     * @param original the string to be encoded
+     * @return The encoded string, {@code null} if the given string is null
+     * @throws UnsupportedEncodingException if chars that are not supported are
+     *                                      encountered
      */
-    @SuppressWarnings("PMD")
-    private void addSingleEncoding(final int level,
-                                   final String currentEncoding,
-                                   final Collection<Integer> encoding,
-                                   final Iterator<Integer> originals,
-                                   final Map<Integer, String> doNotEncodeMap) {
-
-        if (level > 0) {
-            for (final int encodingLetter : encoding) {
-                if (!originals.hasNext()) {
-                    return; // done encoding all the original alphabet
-                }
-                // this skips the doNotEncode chars if they are in the
-                // leftmost place
-                if (level != encodedLetterLength
-                        || !doNotEncodeMap.containsKey(encodingLetter)) {
-                    addSingleEncoding(level - 1,
-                            currentEncoding
-                                    + codePointToString(encodingLetter),
-                            encoding,
-                            originals,
-                            doNotEncodeMap
-                    );
-                }
-            }
-        } else {
-            Integer next = originals.next();
-
-            while (doNotEncodeMap.containsKey(next)) {
-                final String originalLetterAsString = codePointToString(next);
-
-                originalToEncoded.put(next, originalLetterAsString);
-                encodedToOriginal.put(originalLetterAsString,
-                        originalLetterAsString);
+    public String encode(final String original)
+            throws UnsupportedEncodingException {
+        if (original == null) {
+            return null;
+        }
 
-                if (!originals.hasNext()) {
-                    return;
-                }
+        final StringBuilder sb = new StringBuilder();
 
-                next = originals.next();
-            }
+        for (int i = 0; i < original.length();) {
+            final int codepoint = original.codePointAt(i);
 
-            final String originalLetterAsString = codePointToString(next);
+            final String nextLetter = originalToEncoded.get(codepoint);
 
-            originalToEncoded.put(next, currentEncoding);
-            encodedToOriginal.put(currentEncoding, originalLetterAsString);
-        }
-    }
+            if (nextLetter == null) {
+                throw new UnsupportedEncodingException(
+                        "Couldn't find encoding for '"
+                                + codePointToString(codepoint)
+                                + "' in "
+                                + original
+                );
+            }
 
-    @Override
-    public String toString() {
-        final StringBuilder sb = new StringBuilder();
+            sb.append(nextLetter);
 
-        for (final Entry<Integer, String> entry
-                : originalToEncoded.entrySet()) {
-            sb.append(codePointToString(entry.getKey()))
-                    .append(ARROW)
-                    .append(entry.getValue()).append(System.lineSeparator());
+            i += Character.charCount(codepoint);
         }
 
         return sb.toString();
@@ -306,217 +477,46 @@ public final class AlphabetConverter {
                 && encodedLetterLength == other.encodedLetterLength;
     }
 
-    @Override
-    public int hashCode() {
-        return Objects.hash(originalToEncoded,
-                encodedToOriginal,
-                encodedLetterLength);
-    }
-
     /**
-     * Creates a new converter from a map.
+     * Gets the length of characters in the encoded alphabet that are necessary
+     * for each character in the original
+     * alphabet.
      *
-     * @param originalToEncoded a map returned from getOriginalToEncoded()
-     * @return The reconstructed AlphabetConverter
-     * @see AlphabetConverter#getOriginalToEncoded()
+     * @return The length of the encoded char
      */
-    public static AlphabetConverter createConverterFromMap(
-            final Map<Integer, String> originalToEncoded) {
-        final Map<Integer, String> unmodifiableOriginalToEncoded =
-                Collections.unmodifiableMap(originalToEncoded);
-        final Map<String, String> encodedToOriginal = new LinkedHashMap<>();
-
-        int encodedLetterLength = 1;
-
-        for (final Entry<Integer, String> e
-                : unmodifiableOriginalToEncoded.entrySet()) {
-            final String originalAsString = codePointToString(e.getKey());
-            encodedToOriginal.put(e.getValue(), originalAsString);
-
-            if (e.getValue().length() > encodedLetterLength) {
-                encodedLetterLength = e.getValue().length();
-            }
-        }
-
-        return new AlphabetConverter(unmodifiableOriginalToEncoded,
-                encodedToOriginal,
-                encodedLetterLength);
+    public int getEncodedCharLength() {
+        return encodedLetterLength;
     }
 
     /**
-     * Creates an alphabet converter, for converting from the original alphabet,
-     * to the encoded alphabet, while leaving the characters in
-     * <em>doNotEncode</em> as they are (if possible).
-     *
-     * <p>Duplicate letters in either original or encoding will be ignored.</p>
+     * Gets the mapping from integer code point of source language to encoded
+     * string. Use to reconstruct converter from
+     * serialized map.
      *
-     * @param original an array of chars representing the original alphabet
-     * @param encoding an array of chars representing the alphabet to be used
-     *                 for encoding
-     * @param doNotEncode an array of chars to be encoded using the original
-     *                    alphabet - every char here must appear in
-     *                    both the previous params
-     * @return The AlphabetConverter
-     * @throws IllegalArgumentException if an AlphabetConverter cannot be
-     *                                  constructed
+     * @return The original map
      */
-    public static AlphabetConverter createConverterFromChars(
-            final Character[] original,
-            final Character[] encoding,
-            final Character[] doNotEncode) {
-        return AlphabetConverter.createConverter(
-                convertCharsToIntegers(original),
-                convertCharsToIntegers(encoding),
-                convertCharsToIntegers(doNotEncode));
+    public Map<Integer, String> getOriginalToEncoded() {
+        return Collections.unmodifiableMap(originalToEncoded);
     }
 
-    /**
-     * Converts characters to integers.
-     *
-     * @param chars array of characters
-     * @return an equivalent array of integers
-     */
-    private static Integer[] convertCharsToIntegers(final Character[] chars) {
-        if (ArrayUtils.isEmpty(chars)) {
-            return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;
-        }
-        final Integer[] integers = new Integer[chars.length];
-        for (int i = 0; i < chars.length; i++) {
-            integers[i] = (int) chars[i];
-        }
-        return integers;
+    @Override
+    public int hashCode() {
+        return Objects.hash(originalToEncoded,
+                encodedToOriginal,
+                encodedLetterLength);
     }
 
-    /**
-     * Creates an alphabet converter, for converting from the original alphabet,
-     * to the encoded alphabet, while leaving
-     * the characters in <em>doNotEncode</em> as they are (if possible).
-     *
-     * <p>Duplicate letters in either original or encoding will be ignored.</p>
-     *
-     * @param original an array of ints representing the original alphabet in
-     *                 codepoints
-     * @param encoding an array of ints representing the alphabet to be used for
-     *                 encoding, in codepoints
-     * @param doNotEncode an array of ints representing the chars to be encoded
-     *                    using the original alphabet - every char
-     *                    here must appear in both the previous params
-     * @return The AlphabetConverter
-     * @throws IllegalArgumentException if an AlphabetConverter cannot be
-     *                                   constructed
-     */
-    public static AlphabetConverter createConverter(
-            final Integer[] original,
-            final Integer[] encoding,
-            final Integer[] doNotEncode) {
-        final Set<Integer> originalCopy = new LinkedHashSet<>(Arrays.asList(original));
-        final Set<Integer> encodingCopy = new LinkedHashSet<>(Arrays.asList(encoding));
-        final Set<Integer> doNotEncodeCopy = new LinkedHashSet<>(Arrays.asList(doNotEncode));
-
-        final Map<Integer, String> originalToEncoded = new LinkedHashMap<>();
-        final Map<String, String> encodedToOriginal = new LinkedHashMap<>();
-        final Map<Integer, String> doNotEncodeMap = new HashMap<>();
-
-        final int encodedLetterLength;
-
-        for (final int i : doNotEncodeCopy) {
-            if (!originalCopy.contains(i)) {
-                throw new IllegalArgumentException(
-                        "Can not use 'do not encode' list because original "
-                                + "alphabet does not contain '"
-                                + codePointToString(i) + "'");
-            }
-
-            if (!encodingCopy.contains(i)) {
-                throw new IllegalArgumentException(
-                        "Can not use 'do not encode' list because encoding alphabet does not contain '"
-                                + codePointToString(i) + "'");
-            }
-
-            doNotEncodeMap.put(i, codePointToString(i));
-        }
-
-        if (encodingCopy.size() >= originalCopy.size()) {
-            encodedLetterLength = 1;
-
-            final Iterator<Integer> it = encodingCopy.iterator();
-
-            for (final int originalLetter : originalCopy) {
-                final String originalLetterAsString =
-                        codePointToString(originalLetter);
-
-                if (doNotEncodeMap.containsKey(originalLetter)) {
-                    originalToEncoded.put(originalLetter,
-                            originalLetterAsString);
-                    encodedToOriginal.put(originalLetterAsString,
-                            originalLetterAsString);
-                } else {
-                    Integer next = it.next();
-
-                    while (doNotEncodeCopy.contains(next)) {
-                        next = it.next();
-                    }
-
-                    final String encodedLetter = codePointToString(next);
-
-                    originalToEncoded.put(originalLetter, encodedLetter);
-                    encodedToOriginal.put(encodedLetter,
-                            originalLetterAsString);
-                }
-            }
-
-            return new AlphabetConverter(originalToEncoded,
-                    encodedToOriginal,
-                    encodedLetterLength);
-
-        }
-        if (encodingCopy.size() - doNotEncodeCopy.size() < 2) {
-            throw new IllegalArgumentException(
-                    "Must have at least two encoding characters (excluding "
-                            + "those in the 'do not encode' list), but has "
-                            + (encodingCopy.size() - doNotEncodeCopy.size()));
-        }
-        // we start with one which is our minimum, and because we do the
-        // first division outside the loop
-        int lettersSoFar = 1;
-
-        // the first division takes into account that the doNotEncode
-        // letters can't be in the leftmost place
-        int lettersLeft = (originalCopy.size() - doNotEncodeCopy.size())
-                / (encodingCopy.size() - doNotEncodeCopy.size());
+    @Override
+    public String toString() {
+        final StringBuilder sb = new StringBuilder();
 
-        while (lettersLeft / encodingCopy.size() >= 1) {
-            lettersLeft = lettersLeft / encodingCopy.size();
-            lettersSoFar++;
+        for (final Entry<Integer, String> entry
+                : originalToEncoded.entrySet()) {
+            sb.append(codePointToString(entry.getKey()))
+                    .append(ARROW)
+                    .append(entry.getValue()).append(System.lineSeparator());
         }
 
-        encodedLetterLength = lettersSoFar + 1;
-
-        final AlphabetConverter ac =
-                new AlphabetConverter(originalToEncoded,
-                        encodedToOriginal,
-                        encodedLetterLength);
-
-        ac.addSingleEncoding(encodedLetterLength,
-                StringUtils.EMPTY,
-                encodingCopy,
-                originalCopy.iterator(),
-                doNotEncodeMap);
-
-        return ac;
-    }
-
-    /**
-     * Creates new String that contains just the given code point.
-     *
-     * @param i code point
-     * @return a new string with the new code point
-     * @see "http://www.oracle.com/us/technologies/java/supplementary-142654.html"
-     */
-    private static String codePointToString(final int i) {
-        if (Character.charCount(i) == 1) {
-            return String.valueOf((char) i);
-        }
-        return new String(Character.toChars(i));
+        return sb.toString();
     }
 }
diff --git a/src/main/java/org/apache/commons/text/CaseUtils.java b/src/main/java/org/apache/commons/text/CaseUtils.java
index 497e5ee..c3a7591 100644
--- a/src/main/java/org/apache/commons/text/CaseUtils.java
+++ b/src/main/java/org/apache/commons/text/CaseUtils.java
@@ -34,17 +34,6 @@ import org.apache.commons.lang3.StringUtils;
 public class CaseUtils {
 
     /**
-     * {@code CaseUtils} instances should NOT be constructed in
-     * standard programming. Instead, the class should be used as
-     * {@code CaseUtils.toCamelCase("foo bar", true, new char[]{'-'});}.
-     *
-     * <p>This constructor is public to permit tools that require a JavaBean
-     * instance to operate.</p>
-     */
-    public CaseUtils() {
-    }
-
-    /**
      * Converts all the delimiter separated words in a String into camelCase,
      * that is each word is made up of a title case character and then a series of
      * lowercase characters.
@@ -126,5 +115,16 @@ public class CaseUtils {
         }
         return delimiterHashSet;
     }
+
+    /**
+     * {@code CaseUtils} instances should NOT be constructed in
+     * standard programming. Instead, the class should be used as
+     * {@code CaseUtils.toCamelCase("foo bar", true, new char[]{'-'});}.
+     *
+     * <p>This constructor is public to permit tools that require a JavaBean
+     * instance to operate.</p>
+     */
+    public CaseUtils() {
+    }
 }
 
diff --git a/src/main/java/org/apache/commons/text/CompositeFormat.java b/src/main/java/org/apache/commons/text/CompositeFormat.java
index a53ca67..24328ff 100644
--- a/src/main/java/org/apache/commons/text/CompositeFormat.java
+++ b/src/main/java/org/apache/commons/text/CompositeFormat.java
@@ -71,18 +71,12 @@ public class CompositeFormat extends Format {
     }
 
     /**
-     * Parses the input.
+     * Gets the parser Format implementation.
      *
-     * @param source the String source
-     * @param pos the ParsePosition containing the position to parse from, will
-     *            be updated according to parsing success (index) or failure
-     *            (error index)
-     * @return The parsed Object
-     * @see Format#parseObject(String, ParsePosition)
+     * @return formatter Format implementation
      */
-    @Override
-    public Object parseObject(final String source, final ParsePosition pos) {
-        return parser.parseObject(source, pos);
+    public Format getFormatter() {
+        return this.formatter;
     }
 
     /**
@@ -95,12 +89,18 @@ public class CompositeFormat extends Format {
     }
 
     /**
-     * Gets the parser Format implementation.
+     * Parses the input.
      *
-     * @return formatter Format implementation
+     * @param source the String source
+     * @param pos the ParsePosition containing the position to parse from, will
+     *            be updated according to parsing success (index) or failure
+     *            (error index)
+     * @return The parsed Object
+     * @see Format#parseObject(String, ParsePosition)
      */
-    public Format getFormatter() {
-        return this.formatter;
+    @Override
+    public Object parseObject(final String source, final ParsePosition pos) {
+        return parser.parseObject(source, pos);
     }
 
     /**
diff --git a/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java b/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java
index f9682ff..f64ff60 100644
--- a/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java
+++ b/src/main/java/org/apache/commons/text/ExtendedMessageFormat.java
@@ -138,42 +138,71 @@ public class ExtendedMessageFormat extends MessageFormat {
     }
 
     /**
-     * Constructs a new ExtendedMessageFormat for the default locale.
+     * Constructs a new ExtendedMessageFormat.
      *
      * @param pattern  the pattern to use, not null
+     * @param locale  the locale to use, not null
      * @param registry  the registry of format factories, may be null
      * @throws IllegalArgumentException in case of a bad pattern.
      */
     public ExtendedMessageFormat(final String pattern,
+                                 final Locale locale,
                                  final Map<String, ? extends FormatFactory> registry) {
-        this(pattern, Locale.getDefault(Category.FORMAT), registry);
+        super(DUMMY_PATTERN);
+        setLocale(locale);
+        this.registry = registry != null
+                ? Collections.unmodifiableMap(new HashMap<>(registry))
+                : null;
+        applyPattern(pattern);
     }
 
     /**
-     * Constructs a new ExtendedMessageFormat.
+     * Constructs a new ExtendedMessageFormat for the default locale.
      *
      * @param pattern  the pattern to use, not null
-     * @param locale  the locale to use, not null
      * @param registry  the registry of format factories, may be null
      * @throws IllegalArgumentException in case of a bad pattern.
      */
     public ExtendedMessageFormat(final String pattern,
-                                 final Locale locale,
                                  final Map<String, ? extends FormatFactory> registry) {
-        super(DUMMY_PATTERN);
-        setLocale(locale);
-        this.registry = registry != null
-                ? Collections.unmodifiableMap(new HashMap<>(registry))
-                : null;
-        applyPattern(pattern);
+        this(pattern, Locale.getDefault(Category.FORMAT), registry);
     }
 
     /**
-     * {@inheritDoc}
+     * Consumes a quoted string, adding it to {@code appendTo} if
+     * specified.
+     *
+     * @param pattern pattern to parse
+     * @param pos current parse position
+     * @param appendTo optional StringBuilder to append
      */
-    @Override
-    public String toPattern() {
-        return toPattern;
+    private void appendQuotedString(final String pattern, final ParsePosition pos,
+            final StringBuilder appendTo) {
+        assert pattern.toCharArray()[pos.getIndex()] == QUOTE
+                : "Quoted string must start with quote character";
+
+        // handle quote character at the beginning of the string
+        if (appendTo != null) {
+            appendTo.append(QUOTE);
+        }
+        next(pos);
+
+        final int start = pos.getIndex();
+        final char[] c = pattern.toCharArray();
+        for (int i = pos.getIndex(); i < pattern.length(); i++) {
+            switch (c[pos.getIndex()]) {
+            case QUOTE:
+                next(pos);
+                if (appendTo != null) {
+                    appendTo.append(c, start, pos.getIndex() - start);
+                }
+                return;
+            default:
+                next(pos);
+            }
+        }
+        throw new IllegalArgumentException(
+                "Unterminated quoted string at position " + start);
     }
 
     /**
@@ -253,54 +282,20 @@ public class ExtendedMessageFormat extends MessageFormat {
     }
 
     /**
-     * Throws UnsupportedOperationException - see class Javadoc for details.
-     *
-     * @param formatElementIndex format element index
-     * @param newFormat the new format
-     * @throws UnsupportedOperationException always thrown since this isn't
-     *                                       supported by ExtendMessageFormat
-     */
-    @Override
-    public void setFormat(final int formatElementIndex, final Format newFormat) {
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Throws UnsupportedOperationException - see class Javadoc for details.
-     *
-     * @param argumentIndex argument index
-     * @param newFormat the new format
-     * @throws UnsupportedOperationException always thrown since this isn't
-     *                                       supported by ExtendMessageFormat
-     */
-    @Override
-    public void setFormatByArgumentIndex(final int argumentIndex,
-                                         final Format newFormat) {
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Throws UnsupportedOperationException - see class Javadoc for details.
-     *
-     * @param newFormats new formats
-     * @throws UnsupportedOperationException always thrown since this isn't
-     *                                       supported by ExtendMessageFormat
-     */
-    @Override
-    public void setFormats(final Format[] newFormats) {
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * Throws UnsupportedOperationException - see class Javadoc for details.
-     *
-     * @param newFormats new formats
-     * @throws UnsupportedOperationException always thrown since this isn't
-     *                                       supported by ExtendMessageFormat
+     * Tests whether the specified Collection contains non-null elements.
+     * @param coll to check
+     * @return {@code true} if some Object was found, {@code false} otherwise.
      */
-    @Override
-    public void setFormatsByArgumentIndex(final Format[] newFormats) {
-        throw new UnsupportedOperationException();
+    private boolean containsElements(final Collection<?> coll) {
+        if (coll == null || coll.isEmpty()) {
+            return false;
+        }
+        for (final Object name : coll) {
+            if (name != null) {
+                return true;
+            }
+        }
+        return false;
     }
 
     /**
@@ -331,17 +326,6 @@ public class ExtendedMessageFormat extends MessageFormat {
     }
 
     /**
-     * {@inheritDoc}
-     */
-    @Override
-    public int hashCode() {
-        int result = super.hashCode();
-        result = HASH_SEED * result + Objects.hashCode(registry);
-        result = HASH_SEED * result + Objects.hashCode(toPattern);
-        return result;
-    }
-
-    /**
      * Gets a custom format from a format description.
      *
      * @param desc String
@@ -365,82 +349,24 @@ public class ExtendedMessageFormat extends MessageFormat {
     }
 
     /**
-     * Reads the argument index from the current format element.
+     * Consumes quoted string only.
      *
      * @param pattern pattern to parse
      * @param pos current parse position
-     * @return argument index
      */
-    private int readArgumentIndex(final String pattern, final ParsePosition pos) {
-        final int start = pos.getIndex();
-        seekNonWs(pattern, pos);
-        final StringBuilder result = new StringBuilder();
-        boolean error = false;
-        for (; !error && pos.getIndex() < pattern.length(); next(pos)) {
-            char c = pattern.charAt(pos.getIndex());
-            if (Character.isWhitespace(c)) {
-                seekNonWs(pattern, pos);
-                c = pattern.charAt(pos.getIndex());
-                if (c != START_FMT && c != END_FE) {
-                    error = true;
-                    continue;
-                }
-            }
-            if ((c == START_FMT || c == END_FE) && result.length() > 0) {
-                try {
-                    return Integer.parseInt(result.toString());
-                } catch (final NumberFormatException e) { // NOPMD
-                    // we've already ensured only digits, so unless something
-                    // outlandishly large was specified we should be okay.
-                }
-            }
-            error = !Character.isDigit(c);
-            result.append(c);
-        }
-        if (error) {
-            throw new IllegalArgumentException(
-                    "Invalid format argument index at position " + start + ": "
-                            + pattern.substring(start, pos.getIndex()));
-        }
-        throw new IllegalArgumentException(
-                "Unterminated format element at position " + start);
+    private void getQuotedString(final String pattern, final ParsePosition pos) {
+        appendQuotedString(pattern, pos, null);
     }
 
     /**
-     * Parses the format component of a format element.
-     *
-     * @param pattern string to parse
-     * @param pos current parse position
-     * @return Format description String
+     * {@inheritDoc}
      */
-    private String parseFormatDescription(final String pattern, final ParsePosition pos) {
-        final int start = pos.getIndex();
-        seekNonWs(pattern, pos);
-        final int text = pos.getIndex();
-        int depth = 1;
-        while (pos.getIndex() < pattern.length()) {
-            switch (pattern.charAt(pos.getIndex())) {
-            case START_FE:
-                depth++;
-                next(pos);
-                break;
-            case END_FE:
-                depth--;
-                if (depth == 0) {
-                    return pattern.substring(text, pos.getIndex());
-                }
-                next(pos);
-                break;
-            case QUOTE:
-                getQuotedString(pattern, pos);
-                break;
-            default:
-                next(pos);
-                break;
-            }
-        }
-        throw new IllegalArgumentException(
-                "Unterminated format element at position " + start);
+    @Override
+    public int hashCode() {
+        int result = super.hashCode();
+        result = HASH_SEED * result + Objects.hashCode(registry);
+        result = HASH_SEED * result + Objects.hashCode(toPattern);
+        return result;
     }
 
     /**
@@ -488,21 +414,6 @@ public class ExtendedMessageFormat extends MessageFormat {
     }
 
     /**
-     * Consumes whitespace from the current parse position.
-     *
-     * @param pattern String to read
-     * @param pos current position
-     */
-    private void seekNonWs(final String pattern, final ParsePosition pos) {
-        int len = 0;
-        final char[] buffer = pattern.toCharArray();
-        do {
-            len = StringMatcherFactory.INSTANCE.splitMatcher().isMatch(buffer, pos.getIndex(), 0, buffer.length);
-            pos.setIndex(pos.getIndex() + len);
-        } while (len > 0 && pos.getIndex() < pattern.length());
-    }
-
-    /**
      * Advances parse position by 1.
      *
      * @param pos ParsePosition
@@ -514,66 +425,155 @@ public class ExtendedMessageFormat extends MessageFormat {
     }
 
     /**
-     * Consumes a quoted string, adding it to {@code appendTo} if
-     * specified.
+     * Parses the format component of a format element.
      *
-     * @param pattern pattern to parse
+     * @param pattern string to parse
      * @param pos current parse position
-     * @param appendTo optional StringBuilder to append
+     * @return Format description String
      */
-    private void appendQuotedString(final String pattern, final ParsePosition pos,
-            final StringBuilder appendTo) {
-        assert pattern.toCharArray()[pos.getIndex()] == QUOTE
-                : "Quoted string must start with quote character";
-
-        // handle quote character at the beginning of the string
-        if (appendTo != null) {
-            appendTo.append(QUOTE);
-        }
-        next(pos);
-
+    private String parseFormatDescription(final String pattern, final ParsePosition pos) {
         final int start = pos.getIndex();
-        final char[] c = pattern.toCharArray();
-        for (int i = pos.getIndex(); i < pattern.length(); i++) {
-            switch (c[pos.getIndex()]) {
-            case QUOTE:
+        seekNonWs(pattern, pos);
+        final int text = pos.getIndex();
+        int depth = 1;
+        while (pos.getIndex() < pattern.length()) {
+            switch (pattern.charAt(pos.getIndex())) {
+            case START_FE:
+                depth++;
                 next(pos);
-                if (appendTo != null) {
-                    appendTo.append(c, start, pos.getIndex() - start);
+                break;
+            case END_FE:
+                depth--;
+                if (depth == 0) {
+                    return pattern.substring(text, pos.getIndex());
                 }
-                return;
+                next(pos);
+                break;
+            case QUOTE:
+                getQuotedString(pattern, pos);
+                break;
             default:
                 next(pos);
+                break;
             }
         }
         throw new IllegalArgumentException(
-                "Unterminated quoted string at position " + start);
+                "Unterminated format element at position " + start);
     }
 
     /**
-     * Consumes quoted string only.
+     * Reads the argument index from the current format element.
      *
      * @param pattern pattern to parse
      * @param pos current parse position
+     * @return argument index
      */
-    private void getQuotedString(final String pattern, final ParsePosition pos) {
-        appendQuotedString(pattern, pos, null);
+    private int readArgumentIndex(final String pattern, final ParsePosition pos) {
+        final int start = pos.getIndex();
+        seekNonWs(pattern, pos);
+        final StringBuilder result = new StringBuilder();
+        boolean error = false;
+        for (; !error && pos.getIndex() < pattern.length(); next(pos)) {
+            char c = pattern.charAt(pos.getIndex());
+            if (Character.isWhitespace(c)) {
+                seekNonWs(pattern, pos);
+                c = pattern.charAt(pos.getIndex());
+                if (c != START_FMT && c != END_FE) {
+                    error = true;
+                    continue;
+                }
+            }
+            if ((c == START_FMT || c == END_FE) && result.length() > 0) {
+                try {
+                    return Integer.parseInt(result.toString());
+                } catch (final NumberFormatException e) { // NOPMD
+                    // we've already ensured only digits, so unless something
+                    // outlandishly large was specified we should be okay.
+                }
+            }
+            error = !Character.isDigit(c);
+            result.append(c);
+        }
+        if (error) {
+            throw new IllegalArgumentException(
+                    "Invalid format argument index at position " + start + ": "
+                            + pattern.substring(start, pos.getIndex()));
+        }
+        throw new IllegalArgumentException(
+                "Unterminated format element at position " + start);
     }
 
     /**
-     * Tests whether the specified Collection contains non-null elements.
-     * @param coll to check
-     * @return {@code true} if some Object was found, {@code false} otherwise.
+     * Consumes whitespace from the current parse position.
+     *
+     * @param pattern String to read
+     * @param pos current position
      */
-    private boolean containsElements(final Collection<?> coll) {
-        if (coll == null || coll.isEmpty()) {
-            return false;
-        }
-        for (final Object name : coll) {
-            if (name != null) {
-                return true;
-            }
-        }
-        return false;
+    private void seekNonWs(final String pattern, final ParsePosition pos) {
+        int len = 0;
+        final char[] buffer = pattern.toCharArray();
+        do {
+            len = StringMatcherFactory.INSTANCE.splitMatcher().isMatch(buffer, pos.getIndex(), 0, buffer.length);
+            pos.setIndex(pos.getIndex() + len);
+        } while (len > 0 && pos.getIndex() < pattern.length());
+    }
+
+    /**
+     * Throws UnsupportedOperationException - see class Javadoc for details.
+     *
+     * @param formatElementIndex format element index
+     * @param newFormat the new format
+     * @throws UnsupportedOperationException always thrown since this isn't
+     *                                       supported by ExtendMessageFormat
+     */
+    @Override
+    public void setFormat(final int formatElementIndex, final Format newFormat) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Throws UnsupportedOperationException - see class Javadoc for details.
+     *
+     * @param argumentIndex argument index
+     * @param newFormat the new format
+     * @throws UnsupportedOperationException always thrown since this isn't
+     *                                       supported by ExtendMessageFormat
+     */
+    @Override
+    public void setFormatByArgumentIndex(final int argumentIndex,
+                                         final Format newFormat) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Throws UnsupportedOperationException - see class Javadoc for details.
+     *
+     * @param newFormats new formats
+     * @throws UnsupportedOperationException always thrown since this isn't
+     *                                       supported by ExtendMessageFormat
+     */
+    @Override
+    public void setFormats(final Format[] newFormats) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Throws UnsupportedOperationException - see class Javadoc for details.
+     *
+     * @param newFormats new formats
+     * @throws UnsupportedOperationException always thrown since this isn't
+     *                                       supported by ExtendMessageFormat
+     */
+    @Override
+    public void setFormatsByArgumentIndex(final Format[] newFormats) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public String toPattern() {
+        return toPattern;
     }
 }
diff --git a/src/main/java/org/apache/commons/text/FormattableUtils.java b/src/main/java/org/apache/commons/text/FormattableUtils.java
index 6f4936d..62a2380 100644
--- a/src/main/java/org/apache/commons/text/FormattableUtils.java
+++ b/src/main/java/org/apache/commons/text/FormattableUtils.java
@@ -41,28 +41,6 @@ public class FormattableUtils {
     private static final String SIMPLEST_FORMAT = "%s";
 
     /**
-     * {@code FormattableUtils} instances should NOT be constructed in
-     * standard programming. Instead, the methods of the class should be invoked
-     * statically.
-     *
-     * <p>This constructor is public to permit tools that require a JavaBean
-     * instance to operate.</p>
-     */
-    public FormattableUtils() {
-    }
-
-    /**
-     * Gets the default formatted representation of the specified
-     * {@code Formattable}.
-     *
-     * @param formattable  the instance to convert to a string, not null
-     * @return The resulting string, not null
-     */
-    public static String toString(final Formattable formattable) {
-        return String.format(SIMPLEST_FORMAT, formattable);
-    }
-
-    /**
      * Handles the common {@code Formattable} operations of truncate-pad-append,
      * with no ellipsis on precision overflow, and padding width underflow with
      * spaces.
@@ -97,24 +75,6 @@ public class FormattableUtils {
     }
 
     /**
-     * Handles the common {@link Formattable} operations of truncate-pad-append,
-     * padding width underflow with spaces.
-     *
-     * @param seq  the string to handle, not null
-     * @param formatter  the destination formatter, not null
-     * @param flags  the flags for formatting, see {@code Formattable}
-     * @param width  the width of the output, see {@code Formattable}
-     * @param precision  the precision of the output, see {@code Formattable}
-     * @param ellipsis  the ellipsis to use when precision dictates truncation, null or
-     *  empty causes a hard truncation
-     * @return The {@code formatter} instance, not null
-     */
-    public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
-            final int precision, final CharSequence ellipsis) {
-        return append(seq, formatter, flags, width, precision, ' ', ellipsis);
-    }
-
-    /**
      * Handles the common {@link Formattable} operations of truncate-pad-append.
      *
      * @param seq  the string to handle, not null
@@ -153,4 +113,44 @@ public class FormattableUtils {
         return formatter;
     }
 
+    /**
+     * Handles the common {@link Formattable} operations of truncate-pad-append,
+     * padding width underflow with spaces.
+     *
+     * @param seq  the string to handle, not null
+     * @param formatter  the destination formatter, not null
+     * @param flags  the flags for formatting, see {@code Formattable}
+     * @param width  the width of the output, see {@code Formattable}
+     * @param precision  the precision of the output, see {@code Formattable}
+     * @param ellipsis  the ellipsis to use when precision dictates truncation, null or
+     *  empty causes a hard truncation
+     * @return The {@code formatter} instance, not null
+     */
+    public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
+            final int precision, final CharSequence ellipsis) {
+        return append(seq, formatter, flags, width, precision, ' ', ellipsis);
+    }
+
+    /**
+     * Gets the default formatted representation of the specified
+     * {@code Formattable}.
+     *
+     * @param formattable  the instance to convert to a string, not null
+     * @return The resulting string, not null
+     */
+    public static String toString(final Formattable formattable) {
+        return String.format(SIMPLEST_FORMAT, formattable);
+    }
+
+    /**
+     * {@code FormattableUtils} instances should NOT be constructed in
+     * standard programming. Instead, the methods of the class should be invoked
+     * statically.
+     *
+     * <p>This constructor is public to permit tools that require a JavaBean
+     * instance to operate.</p>
+     */
+    public FormattableUtils() {
+    }
+
 }
diff --git a/src/main/java/org/apache/commons/text/RandomStringGenerator.java b/src/main/java/org/apache/commons/text/RandomStringGenerator.java
index 62f127d..ead0148 100644
--- a/src/main/java/org/apache/commons/text/RandomStringGenerator.java
+++ b/src/main/java/org/apache/commons/text/RandomStringGenerator.java
@@ -60,175 +60,6 @@ import org.apache.commons.lang3.Validate;
 public final class RandomStringGenerator {
 
     /**
-     * The smallest allowed code point (inclusive).
-     */
-    private final int minimumCodePoint;
-
-    /**
-     * The largest allowed code point (inclusive).
-     */
-    private final int maximumCodePoint;
-
-    /**
-     * Filters for code points.
-     */
-    private final Set<CharacterPredicate> inclusivePredicates;
-
-    /**
-     * The source of randomness for this generator.
-     */
-    private final TextRandomProvider random;
-
-    /**
-     * The source of provided characters.
-     */
-    private final List<Character> characterList;
-
-    /**
-     * Constructs the generator.
-     *
-     * @param minimumCodePoint
-     *            smallest allowed code point (inclusive)
-     * @param maximumCodePoint
-     *            largest allowed code point (inclusive)
-     * @param inclusivePredicates
-     *            filters for code points
-     * @param random
-     *            source of randomness
-     * @param characterList list of predefined set of characters.
-     */
-    private RandomStringGenerator(final int minimumCodePoint, final int maximumCodePoint,
-                                  final Set<CharacterPredicate> inclusivePredicates, final TextRandomProvider random,
-                                  final List<Character> characterList) {
-        this.minimumCodePoint = minimumCodePoint;
-        this.maximumCodePoint = maximumCodePoint;
-        this.inclusivePredicates = inclusivePredicates;
-        this.random = random;
-        this.characterList = characterList;
-    }
-
-    /**
-     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
-     * or the user-supplied source of randomness.
-     *
-     * @param minInclusive
-     *            the minimum value allowed
-     * @param maxInclusive
-     *            the maximum value allowed
-     * @return The random number.
-     */
-    private int generateRandomNumber(final int minInclusive, final int maxInclusive) {
-        if (random != null) {
-            return random.nextInt(maxInclusive - minInclusive + 1) + minInclusive;
-        }
-        return ThreadLocalRandom.current().nextInt(minInclusive, maxInclusive + 1);
-    }
-
-    /**
-     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
-     * or the user-supplied source of randomness.
-     *
-     * @param characterList predefined char list.
-     * @return The random number.
-     */
-    private int generateRandomNumber(final List<Character> characterList) {
-        final int listSize = characterList.size();
-        if (random != null) {
-            return String.valueOf(characterList.get(random.nextInt(listSize))).codePointAt(0);
-        }
-        return String.valueOf(characterList.get(ThreadLocalRandom.current().nextInt(0, listSize))).codePointAt(0);
-    }
-
-    /**
-     * Generates a random string, containing the specified number of code points.
-     *
-     * <p>
-     * Code points are randomly selected between the minimum and maximum values defined
-     * in the generator.
-     * Surrogate and private use characters are not returned, although the
-     * resulting string may contain pairs of surrogates that together encode a
-     * supplementary character.
-     * </p>
-     * <p>
-     * Note: the number of {@code char} code units generated will exceed
-     * {@code length} if the string contains supplementary characters. See the
-     * {@link Character} documentation to understand how Java stores Unicode
-     * values.
-     * </p>
-     *
-     * @param length
-     *            the number of code points to generate
-     * @return The generated string
-     * @throws IllegalArgumentException
-     *             if {@code length < 0}
-     */
-    public String generate(final int length) {
-        if (length == 0) {
-            return StringUtils.EMPTY;
-        }
-        Validate.isTrue(length > 0, "Length %d is smaller than zero.", length);
-
-        final StringBuilder builder = new StringBuilder(length);
-        long remaining = length;
-
-        do {
-            final int codePoint;
-            if (characterList != null && !characterList.isEmpty()) {
-                codePoint = generateRandomNumber(characterList);
-            } else {
-                codePoint = generateRandomNumber(minimumCodePoint, maximumCodePoint);
-            }
-            switch (Character.getType(codePoint)) {
-            case Character.UNASSIGNED:
-            case Character.PRIVATE_USE:
-            case Character.SURROGATE:
-                continue;
-            default:
-            }
-
-            if (inclusivePredicates != null) {
-                boolean matchedFilter = false;
-                for (final CharacterPredicate predicate : inclusivePredicates) {
-                    if (predicate.test(codePoint)) {
-                        matchedFilter = true;
-                        break;
-                    }
-                }
-                if (!matchedFilter) {
-                    continue;
-                }
-            }
-
-            builder.appendCodePoint(codePoint);
-            remaining--;
-
-        } while (remaining != 0);
-
-        return builder.toString();
-    }
-
-    /**
-     * Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive)
-     * number of code points.
-     *
-     * @param minLengthInclusive
-     *            the minimum (inclusive) number of code points to generate
-     * @param maxLengthInclusive
-     *            the maximum (inclusive) number of code points to generate
-     * @return The generated string
-     * @throws IllegalArgumentException
-     *             if {@code minLengthInclusive < 0}, or {@code maxLengthInclusive < minLengthInclusive}
-     * @see RandomStringGenerator#generate(int)
-     * @since 1.2
-     */
-    public String generate(final int minLengthInclusive, final int maxLengthInclusive) {
-        Validate.isTrue(minLengthInclusive >= 0, "Minimum length %d is smaller than zero.", minLengthInclusive);
-        Validate.isTrue(minLengthInclusive <= maxLengthInclusive,
-                "Maximum length %d is smaller than minimum length %d.", maxLengthInclusive, minLengthInclusive);
-        return generate(generateRandomNumber(minLengthInclusive, maxLengthInclusive));
-    }
-
-    /**
      * A builder for generating {@code RandomStringGenerator} instances.
      *
      * <p>The behavior of a generator is controlled by properties set by this
@@ -295,66 +126,14 @@ public final class RandomStringGenerator {
         private List<Character> characterList;
 
         /**
-         * Sets the minimum and maximum code points allowed in the
-         * generated string.
-         *
-         * @param minimumCodePoint
-         *            the smallest code point allowed (inclusive)
-         * @param maximumCodePoint
-         *            the largest code point allowed (inclusive)
-         * @return {@code this}, to allow method chaining
-         * @throws IllegalArgumentException
-         *             if {@code maximumCodePoint >}
-         *             {@link Character#MAX_CODE_POINT}
-         * @throws IllegalArgumentException
-         *             if {@code minimumCodePoint < 0}
-         * @throws IllegalArgumentException
-         *             if {@code minimumCodePoint > maximumCodePoint}
-         */
-        public Builder withinRange(final int minimumCodePoint, final int maximumCodePoint) {
-            Validate.isTrue(minimumCodePoint <= maximumCodePoint,
-                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
-            Validate.isTrue(minimumCodePoint >= 0, "Minimum code point %d is negative", minimumCodePoint);
-            Validate.isTrue(maximumCodePoint <= Character.MAX_CODE_POINT,
-                    "Value %d is larger than Character.MAX_CODE_POINT.", maximumCodePoint);
-
-            this.minimumCodePoint = minimumCodePoint;
-            this.maximumCodePoint = maximumCodePoint;
-            return this;
-        }
-
-        /**
-         * Sets the array of minimum and maximum char allowed in the
-         * generated string.
-         *
-         * For example:
-         * <pre>
-         * {@code
-         *     char [][] pairs = {{'0','9'}};
-         *     char [][] pairs = {{'a','z'}};
-         *     char [][] pairs = {{'a','z'},{'0','9'}};
-         * }
-         * </pre>
+         * Builds the {@code RandomStringGenerator} using the properties specified.
          *
-         * @param pairs array of characters array, expected is to pass min, max pairs through this arg.
-         * @return {@code this}, to allow method chaining.
+         * @return The configured {@code RandomStringGenerator}
          */
-        public Builder withinRange(final char[]... pairs) {
-            characterList = new ArrayList<>();
-            for (final char[] pair :  pairs) {
-                Validate.isTrue(pair.length == 2,
-                      "Each pair must contain minimum and maximum code point");
-                final int minimumCodePoint = pair[0];
-                final int maximumCodePoint = pair[1];
-                Validate.isTrue(minimumCodePoint <= maximumCodePoint,
-                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
-
-                for (int index = minimumCodePoint; index <= maximumCodePoint; index++) {
-                    characterList.add((char) index);
-                }
-            }
-            return this;
-
+        @Override
+        public RandomStringGenerator build() {
+            return new RandomStringGenerator(minimumCodePoint, maximumCodePoint, inclusivePredicates,
+                    random, characterList);
         }
 
         /**
@@ -389,6 +168,29 @@ public final class RandomStringGenerator {
         }
 
         /**
+         * Limits the characters in the generated string to those who match at
+         * supplied list of Character.
+         *
+         * <p>
+         * Passing {@code null} or an empty array to this method will revert to the
+         * default behavior of allowing any character. Multiple calls to this
+         * method will replace the previously stored Character.
+         * </p>
+         *
+         * @param chars set of predefined Characters for random string generation
+         *            the Character can be, may be {@code null} or empty
+         * @return {@code this}, to allow method chaining
+         * @since 1.2
+         */
+        public Builder selectFrom(final char... chars) {
+            characterList = new ArrayList<>();
+            for (final char c : chars) {
+                characterList.add(c);
+            }
+            return this;
+        }
+
+        /**
          * Overrides the default source of randomness.  It is highly
          * recommended that a random number generator library like
          * <a href="https://commons.apache.org/proper/commons-rng/">Apache Commons RNG</a>
@@ -423,37 +225,235 @@ public final class RandomStringGenerator {
         }
 
         /**
-         * Limits the characters in the generated string to those who match at
-         * supplied list of Character.
+         * Sets the array of minimum and maximum char allowed in the
+         * generated string.
          *
-         * <p>
-         * Passing {@code null} or an empty array to this method will revert to the
-         * default behavior of allowing any character. Multiple calls to this
-         * method will replace the previously stored Character.
-         * </p>
+         * For example:
+         * <pre>
+         * {@code
+         *     char [][] pairs = {{'0','9'}};
+         *     char [][] pairs = {{'a','z'}};
+         *     char [][] pairs = {{'a','z'},{'0','9'}};
+         * }
+         * </pre>
          *
-         * @param chars set of predefined Characters for random string generation
-         *            the Character can be, may be {@code null} or empty
-         * @return {@code this}, to allow method chaining
-         * @since 1.2
+         * @param pairs array of characters array, expected is to pass min, max pairs through this arg.
+         * @return {@code this}, to allow method chaining.
          */
-        public Builder selectFrom(final char... chars) {
+        public Builder withinRange(final char[]... pairs) {
             characterList = new ArrayList<>();
-            for (final char c : chars) {
-                characterList.add(c);
+            for (final char[] pair :  pairs) {
+                Validate.isTrue(pair.length == 2,
+                      "Each pair must contain minimum and maximum code point");
+                final int minimumCodePoint = pair[0];
+                final int maximumCodePoint = pair[1];
+                Validate.isTrue(minimumCodePoint <= maximumCodePoint,
+                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
+
+                for (int index = minimumCodePoint; index <= maximumCodePoint; index++) {
+                    characterList.add((char) index);
+                }
             }
             return this;
+
         }
 
         /**
-         * Builds the {@code RandomStringGenerator} using the properties specified.
+         * Sets the minimum and maximum code points allowed in the
+         * generated string.
          *
-         * @return The configured {@code RandomStringGenerator}
+         * @param minimumCodePoint
+         *            the smallest code point allowed (inclusive)
+         * @param maximumCodePoint
+         *            the largest code point allowed (inclusive)
+         * @return {@code this}, to allow method chaining
+         * @throws IllegalArgumentException
+         *             if {@code maximumCodePoint >}
+         *             {@link Character#MAX_CODE_POINT}
+         * @throws IllegalArgumentException
+         *             if {@code minimumCodePoint < 0}
+         * @throws IllegalArgumentException
+         *             if {@code minimumCodePoint > maximumCodePoint}
          */
-        @Override
-        public RandomStringGenerator build() {
-            return new RandomStringGenerator(minimumCodePoint, maximumCodePoint, inclusivePredicates,
-                    random, characterList);
+        public Builder withinRange(final int minimumCodePoint, final int maximumCodePoint) {
+            Validate.isTrue(minimumCodePoint <= maximumCodePoint,
+                    "Minimum code point %d is larger than maximum code point %d", minimumCodePoint, maximumCodePoint);
+            Validate.isTrue(minimumCodePoint >= 0, "Minimum code point %d is negative", minimumCodePoint);
+            Validate.isTrue(maximumCodePoint <= Character.MAX_CODE_POINT,
+                    "Value %d is larger than Character.MAX_CODE_POINT.", maximumCodePoint);
+
+            this.minimumCodePoint = minimumCodePoint;
+            this.maximumCodePoint = maximumCodePoint;
+            return this;
         }
     }
+
+    /**
+     * The smallest allowed code point (inclusive).
+     */
+    private final int minimumCodePoint;
+
+    /**
+     * The largest allowed code point (inclusive).
+     */
+    private final int maximumCodePoint;
+
+    /**
+     * Filters for code points.
+     */
+    private final Set<CharacterPredicate> inclusivePredicates;
+
+    /**
+     * The source of randomness for this generator.
+     */
+    private final TextRandomProvider random;
+
+    /**
+     * The source of provided characters.
+     */
+    private final List<Character> characterList;
+
+    /**
+     * Constructs the generator.
+     *
+     * @param minimumCodePoint
+     *            smallest allowed code point (inclusive)
+     * @param maximumCodePoint
+     *            largest allowed code point (inclusive)
+     * @param inclusivePredicates
+     *            filters for code points
+     * @param random
+     *            source of randomness
+     * @param characterList list of predefined set of characters.
+     */
+    private RandomStringGenerator(final int minimumCodePoint, final int maximumCodePoint,
+                                  final Set<CharacterPredicate> inclusivePredicates, final TextRandomProvider random,
+                                  final List<Character> characterList) {
+        this.minimumCodePoint = minimumCodePoint;
+        this.maximumCodePoint = maximumCodePoint;
+        this.inclusivePredicates = inclusivePredicates;
+        this.random = random;
+        this.characterList = characterList;
+    }
+
+    /**
+     * Generates a random string, containing the specified number of code points.
+     *
+     * <p>
+     * Code points are randomly selected between the minimum and maximum values defined
+     * in the generator.
+     * Surrogate and private use characters are not returned, although the
+     * resulting string may contain pairs of surrogates that together encode a
+     * supplementary character.
+     * </p>
+     * <p>
+     * Note: the number of {@code char} code units generated will exceed
+     * {@code length} if the string contains supplementary characters. See the
+     * {@link Character} documentation to understand how Java stores Unicode
+     * values.
+     * </p>
+     *
+     * @param length
+     *            the number of code points to generate
+     * @return The generated string
+     * @throws IllegalArgumentException
+     *             if {@code length < 0}
+     */
+    public String generate(final int length) {
+        if (length == 0) {
+            return StringUtils.EMPTY;
+        }
+        Validate.isTrue(length > 0, "Length %d is smaller than zero.", length);
+
+        final StringBuilder builder = new StringBuilder(length);
+        long remaining = length;
+
+        do {
+            final int codePoint;
+            if (characterList != null && !characterList.isEmpty()) {
+                codePoint = generateRandomNumber(characterList);
+            } else {
+                codePoint = generateRandomNumber(minimumCodePoint, maximumCodePoint);
+            }
+            switch (Character.getType(codePoint)) {
+            case Character.UNASSIGNED:
+            case Character.PRIVATE_USE:
+            case Character.SURROGATE:
+                continue;
+            default:
+            }
+
+            if (inclusivePredicates != null) {
+                boolean matchedFilter = false;
+                for (final CharacterPredicate predicate : inclusivePredicates) {
+                    if (predicate.test(codePoint)) {
+                        matchedFilter = true;
+                        break;
+                    }
+                }
+                if (!matchedFilter) {
+                    continue;
+                }
+            }
+
+            builder.appendCodePoint(codePoint);
+            remaining--;
+
+        } while (remaining != 0);
+
+        return builder.toString();
+    }
+
+    /**
+     * Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive)
+     * number of code points.
+     *
+     * @param minLengthInclusive
+     *            the minimum (inclusive) number of code points to generate
+     * @param maxLengthInclusive
+     *            the maximum (inclusive) number of code points to generate
+     * @return The generated string
+     * @throws IllegalArgumentException
+     *             if {@code minLengthInclusive < 0}, or {@code maxLengthInclusive < minLengthInclusive}
+     * @see RandomStringGenerator#generate(int)
+     * @since 1.2
+     */
+    public String generate(final int minLengthInclusive, final int maxLengthInclusive) {
+        Validate.isTrue(minLengthInclusive >= 0, "Minimum length %d is smaller than zero.", minLengthInclusive);
+        Validate.isTrue(minLengthInclusive <= maxLengthInclusive,
+                "Maximum length %d is smaller than minimum length %d.", maxLengthInclusive, minLengthInclusive);
+        return generate(generateRandomNumber(minLengthInclusive, maxLengthInclusive));
+    }
+
+    /**
+     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
+     * or the user-supplied source of randomness.
+     *
+     * @param minInclusive
+     *            the minimum value allowed
+     * @param maxInclusive
+     *            the maximum value allowed
+     * @return The random number.
+     */
+    private int generateRandomNumber(final int minInclusive, final int maxInclusive) {
+        if (random != null) {
+            return random.nextInt(maxInclusive - minInclusive + 1) + minInclusive;
+        }
+        return ThreadLocalRandom.current().nextInt(minInclusive, maxInclusive + 1);
+    }
+
+    /**
+     * Generates a random number within a range, using a {@link ThreadLocalRandom} instance
+     * or the user-supplied source of randomness.
+     *
+     * @param characterList predefined char list.
+     * @return The random number.
+     */
+    private int generateRandomNumber(final List<Character> characterList) {
+        final int listSize = characterList.size();
+        if (random != null) {
+            return String.valueOf(characterList.get(random.nextInt(listSize))).codePointAt(0);
+        }
+        return String.valueOf(characterList.get(ThreadLocalRandom.current().nextInt(0, listSize))).codePointAt(0);
+    }
 }
diff --git a/src/main/java/org/apache/commons/text/StrLookup.java b/src/main/java/org/apache/commons/text/StrLookup.java
index 3f040b5..b49a2a2 100644
--- a/src/main/java/org/apache/commons/text/StrLookup.java
+++ b/src/main/java/org/apache/commons/text/StrLookup.java
@@ -45,76 +45,6 @@ import org.apache.commons.text.lookup.StringLookupFactory;
 public abstract class StrLookup<V> implements StringLookup {
 
     /**
-     * Lookup that always returns null.
-     */
-    private static final StrLookup<String> NONE_LOOKUP = new MapStrLookup<>(null);
-
-    /**
-     * Lookup based on system properties.
-     */
-    private static final StrLookup<String> SYSTEM_PROPERTIES_LOOKUP = new SystemPropertiesStrLookup();
-
-    /**
-     * Returns a lookup which always returns null.
-     *
-     * @return a lookup that always returns null, not null
-     */
-    public static StrLookup<?> noneLookup() {
-        return NONE_LOOKUP;
-    }
-
-    /**
-     * Returns a new lookup which uses a copy of the current {@link System#getProperties() System properties}.
-     * <p>
-     * If a security manager blocked access to system properties, then null will be returned from every lookup.
-     * </p>
-     * <p>
-     * If a null key is used, this lookup will throw a NullPointerException.
-     * </p>
-     *
-     * @return a lookup using system properties, not null
-     */
-    public static StrLookup<String> systemPropertiesLookup() {
-        return SYSTEM_PROPERTIES_LOOKUP;
-    }
-
-    /**
-     * Returns a lookup which looks up values using a map.
-     * <p>
-     * If the map is null, then null will be returned from every lookup. The map result object is converted to a string
-     * using toString().
-     * </p>
-     *
-     * @param <V> the type of the values supported by the lookup
-     * @param map the map of keys to values, may be null
-     * @return a lookup using the map, not null
-     */
-    public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
-        return new MapStrLookup<>(map);
-    }
-
-    /**
-     * Returns a lookup which looks up values using a ResourceBundle.
-     * <p>
-     * If the ResourceBundle is null, then null will be returned from every lookup. The map result object is converted
-     * to a string using toString().
-     * </p>
-     *
-     * @param resourceBundle the map of keys to values, may be null
-     * @return a lookup using the map, not null
-     * @see StringLookupFactory#resourceBundleStringLookup(String)
-     */
-    public static StrLookup<String> resourceBundleLookup(final ResourceBundle resourceBundle) {
-        return new ResourceBundleLookup(resourceBundle);
-    }
-
-    /**
-     * Constructor.
-     */
-    protected StrLookup() {
-    }
-
-    /**
      * Lookup implementation that uses a Map.
      *
      * @param <V> the type of the values supported by the lookup
@@ -211,4 +141,74 @@ public abstract class StrLookup<V> implements StringLookup {
             return null;
         }
     }
+
+    /**
+     * Lookup that always returns null.
+     */
+    private static final StrLookup<String> NONE_LOOKUP = new MapStrLookup<>(null);
+
+    /**
+     * Lookup based on system properties.
+     */
+    private static final StrLookup<String> SYSTEM_PROPERTIES_LOOKUP = new SystemPropertiesStrLookup();
+
+    /**
+     * Returns a lookup which looks up values using a map.
+     * <p>
+     * If the map is null, then null will be returned from every lookup. The map result object is converted to a string
+     * using toString().
+     * </p>
+     *
+     * @param <V> the type of the values supported by the lookup
+     * @param map the map of keys to values, may be null
+     * @return a lookup using the map, not null
+     */
+    public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
+        return new MapStrLookup<>(map);
+    }
+
+    /**
+     * Returns a lookup which always returns null.
+     *
+     * @return a lookup that always returns null, not null
+     */
+    public static StrLookup<?> noneLookup() {
+        return NONE_LOOKUP;
+    }
+
+    /**
+     * Returns a lookup which looks up values using a ResourceBundle.
+     * <p>
+     * If the ResourceBundle is null, then null will be returned from every lookup. The map result object is converted
+     * to a string using toString().
+     * </p>
+     *
+     * @param resourceBundle the map of keys to values, may be null
+     * @return a lookup using the map, not null
+     * @see StringLookupFactory#resourceBundleStringLookup(String)
+     */
+    public static StrLookup<String> resourceBundleLookup(final ResourceBundle resourceBundle) {
+        return new ResourceBundleLookup(resourceBundle);
+    }
+
+    /**
+     * Returns a new lookup which uses a copy of the current {@link System#getProperties() System properties}.
+     * <p>
+     * If a security manager blocked access to system properties, then null will be returned from every lookup.
+     * </p>
+     * <p>
+     * If a null key is used, this lookup will throw a NullPointerException.
+     * </p>
+     *
+     * @return a lookup using system properties, not null
+     */
+    public static StrLookup<String> systemPropertiesLookup() {
+        return SYSTEM_PROPERTIES_LOOKUP;
+    }
+
+    /**
+     * Constructor.
+     */
+    protected StrLookup() {
+    }
 }
diff --git a/src/main/java/org/apache/commons/text/StrMatcher.java b/src/main/java/org/apache/commons/text/StrMatcher.java
index cf7204a..062f670 100644
--- a/src/main/java/org/apache/commons/text/StrMatcher.java
+++ b/src/main/java/org/apache/commons/text/StrMatcher.java
@@ -36,6 +36,167 @@ import org.apache.commons.text.matcher.StringMatcherFactory;
 public abstract class StrMatcher {
 
     /**
+     * Class used to define a character for matching purposes.
+     */
+    static final class CharMatcher extends StrMatcher {
+        /** The character to match. */
+        private final char ch;
+
+        /**
+         * Constructor that creates a matcher that matches a single character.
+         *
+         * @param ch  the character to match
+         */
+        CharMatcher(final char ch) {
+            this.ch = ch;
+        }
+
+        /**
+         * Returns {@code 1} if there is a match, or {@code 0} if there is no match.
+         *
+         * @param buffer  the text content to match against, do not change
+         * @param pos  the starting position for the match, valid for buffer
+         * @param bufferStart  the first active index in the buffer, valid for buffer
+         * @param bufferEnd  the end index of the active buffer, valid for buffer
+         * @return The number of matching characters, or zero if there is no match
+         */
+        @Override
+        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+            return ch == buffer[pos] ? 1 : 0;
+        }
+    }
+
+    /**
+     * Class used to define a set of characters for matching purposes.
+     */
+    static final class CharSetMatcher extends StrMatcher {
+        /** The set of characters to match. */
+        private final char[] chars;
+
+        /**
+         * Constructor that creates a matcher from a character array.
+         *
+         * @param chars  the characters to match, must not be null
+         */
+        CharSetMatcher(final char[] chars) {
+            this.chars = chars.clone();
+            Arrays.sort(this.chars);
+        }
+
+        /**
+         * Returns {@code 1} if there is a match, or {@code 0} if there is no match.
+         *
+         * @param buffer  the text content to match against, do not change
+         * @param pos  the starting position for the match, valid for buffer
+         * @param bufferStart  the first active index in the buffer, valid for buffer
+         * @param bufferEnd  the end index of the active buffer, valid for buffer
+         * @return The number of matching characters, or zero if there is no match
+         */
+        @Override
+        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+            return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0;
+        }
+    }
+
+    /**
+     * Class used to match no characters.
+     */
+    static final class NoMatcher extends StrMatcher {
+
+        /**
+         * Constructs a new instance of {@code NoMatcher}.
+         */
+        NoMatcher() {
+        }
+
+        /**
+         * Always returns {@code 0}.
+         *
+         * @param buffer  the text content to match against, do not change
+         * @param pos  the starting position for the match, valid for buffer
+         * @param bufferStart  the first active index in the buffer, valid for buffer
+         * @param bufferEnd  the end index of the active buffer, valid for buffer
+         * @return The number of matching characters, or zero if there is no match
+         */
+        @Override
+        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+            return 0;
+        }
+    }
+
+    /**
+     * Class used to define a set of characters for matching purposes.
+     */
+    static final class StringMatcher extends StrMatcher {
+        /** The string to match, as a character array. */
+        private final char[] chars;
+
+        /**
+         * Constructor that creates a matcher from a String.
+         *
+         * @param str  the string to match, must not be null
+         */
+        StringMatcher(final String str) {
+            chars = str.toCharArray();
+        }
+
+        /**
+         * Returns the number of matching characters, or zero if there is no match.
+         *
+         * @param buffer  the text content to match against, do not change
+         * @param pos  the starting position for the match, valid for buffer
+         * @param bufferStart  the first active index in the buffer, valid for buffer
+         * @param bufferEnd  the end index of the active buffer, valid for buffer
+         * @return The number of matching characters, or zero if there is no match
+         */
+        @Override
+        public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
+            final int len = chars.length;
+            if (pos + len > bufferEnd) {
+                return 0;
+            }
+            for (int i = 0; i < chars.length; i++, pos++) {
+                if (chars[i] != buffer[pos]) {
+                    return 0;
+                }
+            }
+            return len;
+        }
+
+        @Override
+        public String toString() {
+            return super.toString() + ' ' + Arrays.toString(chars);
+        }
+
+    }
+
+    /**
+     * Class used to match whitespace as per trim().
+     */
+    static final class TrimMatcher extends StrMatcher {
+
+        /**
+         * Constructs a new instance of {@code TrimMatcher}.
+         */
+        TrimMatcher() {
+        }
+
+        /**
+         * Returns whether or not the given character matches.
+         *
+         * @param buffer  the text content to match against, do not change
+         * @param pos  the starting position for the match, valid for buffer
+         * @param bufferStart  the first active index in the buffer, valid for buffer
+         * @param bufferEnd  the end index of the active buffer, valid for buffer
+         * @return The number of matching characters, or zero if there is no match
+         */
+        @Override
+        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+            return buffer[pos] <= 32 ? 1 : 0;
+        }
+    }
+
+    /**
      * Matches the comma character.
      */
     private static final StrMatcher COMMA_MATCHER = new CharMatcher(',');
@@ -82,58 +243,54 @@ public abstract class StrMatcher {
     private static final StrMatcher NONE_MATCHER = new NoMatcher();
 
     /**
-     * Returns a matcher which matches the comma character.
-     *
-     * @return a matcher for a comma
-     */
-    public static StrMatcher commaMatcher() {
-        return COMMA_MATCHER;
-    }
-
-    /**
-     * Returns a matcher which matches the tab character.
-     *
-     * @return a matcher for a tab
-     */
-    public static StrMatcher tabMatcher() {
-        return TAB_MATCHER;
-    }
-
-    /**
-     * Returns a matcher which matches the space character.
+     * Creates a matcher from a character.
      *
-     * @return a matcher for a space
+     * @param ch  the character to match, must not be null
+     * @return a new Matcher for the given char
      */
-    public static StrMatcher spaceMatcher() {
-        return SPACE_MATCHER;
+    public static StrMatcher charMatcher(final char ch) {
+        return new CharMatcher(ch);
     }
 
     /**
-     * Matches the same characters as StringTokenizer,
-     * namely space, tab, newline and form feed.
+     * Creates a matcher from a set of characters.
      *
-     * @return The split matcher
+     * @param chars  the characters to match, null or empty matches nothing
+     * @return a new matcher for the given char[]
      */
-    public static StrMatcher splitMatcher() {
-        return SPLIT_MATCHER;
+    public static StrMatcher charSetMatcher(final char... chars) {
+        if (ArrayUtils.isEmpty(chars)) {
+            return NONE_MATCHER;
+        }
+        if (chars.length == 1) {
+            return new CharMatcher(chars[0]);
+        }
+        return new CharSetMatcher(chars);
     }
 
     /**
-     * Matches the String trim() whitespace characters.
+     * Creates a matcher from a string representing a set of characters.
      *
-     * @return The trim matcher
+     * @param chars  the characters to match, null or empty matches nothing
+     * @return a new Matcher for the given characters
      */
-    public static StrMatcher trimMatcher() {
-        return TRIM_MATCHER;
+    public static StrMatcher charSetMatcher(final String chars) {
+        if (chars == null || chars.isEmpty()) {
+            return NONE_MATCHER;
+        }
+        if (chars.length() == 1) {
+            return new CharMatcher(chars.charAt(0));
+        }
+        return new CharSetMatcher(chars.toCharArray());
     }
 
     /**
-     * Returns a matcher which matches the single quote character.
+     * Returns a matcher which matches the comma character.
      *
-     * @return a matcher for a single quote
+     * @return a matcher for a comma
      */
-    public static StrMatcher singleQuoteMatcher() {
-        return SINGLE_QUOTE_MATCHER;
+    public static StrMatcher commaMatcher() {
+        return COMMA_MATCHER;
     }
 
     /**
@@ -146,63 +303,49 @@ public abstract class StrMatcher {
     }
 
     /**
-     * Returns a matcher which matches the single or double quote character.
+     * Matches no characters.
      *
-     * @return a matcher for a single or double quote
+     * @return a matcher that matches nothing
      */
-    public static StrMatcher quoteMatcher() {
-        return QUOTE_MATCHER;
+    public static StrMatcher noneMatcher() {
+        return NONE_MATCHER;
     }
 
     /**
-     * Matches no characters.
+     * Returns a matcher which matches the single or double quote character.
      *
-     * @return a matcher that matches nothing
+     * @return a matcher for a single or double quote
      */
-    public static StrMatcher noneMatcher() {
-        return NONE_MATCHER;
+    public static StrMatcher quoteMatcher() {
+        return QUOTE_MATCHER;
     }
 
     /**
-     * Creates a matcher from a character.
+     * Returns a matcher which matches the single quote character.
      *
-     * @param ch  the character to match, must not be null
-     * @return a new Matcher for the given char
+     * @return a matcher for a single quote
      */
-    public static StrMatcher charMatcher(final char ch) {
-        return new CharMatcher(ch);
+    public static StrMatcher singleQuoteMatcher() {
+        return SINGLE_QUOTE_MATCHER;
     }
 
     /**
-     * Creates a matcher from a set of characters.
+     * Returns a matcher which matches the space character.
      *
-     * @param chars  the characters to match, null or empty matches nothing
-     * @return a new matcher for the given char[]
+     * @return a matcher for a space
      */
-    public static StrMatcher charSetMatcher(final char... chars) {
-        if (ArrayUtils.isEmpty(chars)) {
-            return NONE_MATCHER;
-        }
-        if (chars.length == 1) {
-            return new CharMatcher(chars[0]);
-        }
-        return new CharSetMatcher(chars);
+    public static StrMatcher spaceMatcher() {
+        return SPACE_MATCHER;
     }
 
     /**
-     * Creates a matcher from a string representing a set of characters.
+     * Matches the same characters as StringTokenizer,
+     * namely space, tab, newline and form feed.
      *
-     * @param chars  the characters to match, null or empty matches nothing
-     * @return a new Matcher for the given characters
+     * @return The split matcher
      */
-    public static StrMatcher charSetMatcher(final String chars) {
-        if (chars == null || chars.isEmpty()) {
-            return NONE_MATCHER;
-        }
-        if (chars.length() == 1) {
-            return new CharMatcher(chars.charAt(0));
-        }
-        return new CharSetMatcher(chars.toCharArray());
+    public static StrMatcher splitMatcher() {
+        return SPLIT_MATCHER;
     }
 
     /**
@@ -219,6 +362,24 @@ public abstract class StrMatcher {
     }
 
     /**
+     * Returns a matcher which matches the tab character.
+     *
+     * @return a matcher for a tab
+     */
+    public static StrMatcher tabMatcher() {
+        return TAB_MATCHER;
+    }
+
+    /**
+     * Matches the String trim() whitespace characters.
+     *
+     * @return The trim matcher
+     */
+    public static StrMatcher trimMatcher() {
+        return TRIM_MATCHER;
+    }
+
+    /**
      * Constructor.
      */
     protected StrMatcher() {
@@ -234,13 +395,8 @@ public abstract class StrMatcher {
      * The API guarantees that {@code pos} is a valid index for {@code buffer}.
      * </p>
      * <p>
-     * The character array may be larger than the active area to be matched.
-     * Only values in the buffer between the specified indices may be accessed.
-     * </p>
-     * <p>
      * The matching code may check one character or many.
-     * It may check characters preceding {@code pos} as well as those
-     * after, so long as no checks exceed the bounds specified.
+     * It may check characters preceding {@code pos} as well as those after.
      * </p>
      * <p>
      * It must return zero for no match, or a positive number if a match was found.
@@ -249,11 +405,11 @@ public abstract class StrMatcher {
      *
      * @param buffer  the text content to match against, do not change
      * @param pos  the starting position for the match, valid for buffer
-     * @param bufferStart  the first active index in the buffer, valid for buffer
-     * @param bufferEnd  the end index (exclusive) of the active buffer, valid for buffer
      * @return The number of matching characters, or zero if there is no match
      */
-    public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd);
+    public int isMatch(final char[] buffer, final int pos) {
+        return isMatch(buffer, pos, 0, buffer.length);
+    }
 
     /**
      * Returns the number of matching characters, or zero if there is no match.
@@ -265,8 +421,13 @@ public abstract class StrMatcher {
      * The API guarantees that {@code pos} is a valid index for {@code buffer}.
      * </p>
      * <p>
+     * The character array may be larger than the active area to be matched.
+     * Only values in the buffer between the specified indices may be accessed.
+     * </p>
+     * <p>
      * The matching code may check one character or many.
-     * It may check characters preceding {@code pos} as well as those after.
+     * It may check characters preceding {@code pos} as well as those
+     * after, so long as no checks exceed the bounds specified.
      * </p>
      * <p>
      * It must return zero for no match, or a positive number if a match was found.
@@ -275,171 +436,10 @@ public abstract class StrMatcher {
      *
      * @param buffer  the text content to match against, do not change
      * @param pos  the starting position for the match, valid for buffer
+     * @param bufferStart  the first active index in the buffer, valid for buffer
+     * @param bufferEnd  the end index (exclusive) of the active buffer, valid for buffer
      * @return The number of matching characters, or zero if there is no match
      */
-    public int isMatch(final char[] buffer, final int pos) {
-        return isMatch(buffer, pos, 0, buffer.length);
-    }
-
-    /**
-     * Class used to define a set of characters for matching purposes.
-     */
-    static final class CharSetMatcher extends StrMatcher {
-        /** The set of characters to match. */
-        private final char[] chars;
-
-        /**
-         * Constructor that creates a matcher from a character array.
-         *
-         * @param chars  the characters to match, must not be null
-         */
-        CharSetMatcher(final char[] chars) {
-            this.chars = chars.clone();
-            Arrays.sort(this.chars);
-        }
-
-        /**
-         * Returns {@code 1} if there is a match, or {@code 0} if there is no match.
-         *
-         * @param buffer  the text content to match against, do not change
-         * @param pos  the starting position for the match, valid for buffer
-         * @param bufferStart  the first active index in the buffer, valid for buffer
-         * @param bufferEnd  the end index of the active buffer, valid for buffer
-         * @return The number of matching characters, or zero if there is no match
-         */
-        @Override
-        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
-            return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0;
-        }
-    }
-
-    /**
-     * Class used to define a character for matching purposes.
-     */
-    static final class CharMatcher extends StrMatcher {
-        /** The character to match. */
-        private final char ch;
-
-        /**
-         * Constructor that creates a matcher that matches a single character.
-         *
-         * @param ch  the character to match
-         */
-        CharMatcher(final char ch) {
-            this.ch = ch;
-        }
-
-        /**
-         * Returns {@code 1} if there is a match, or {@code 0} if there is no match.
-         *
-         * @param buffer  the text content to match against, do not change
-         * @param pos  the starting position for the match, valid for buffer
-         * @param bufferStart  the first active index in the buffer, valid for buffer
-         * @param bufferEnd  the end index of the active buffer, valid for buffer
-         * @return The number of matching characters, or zero if there is no match
-         */
-        @Override
-        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
-            return ch == buffer[pos] ? 1 : 0;
-        }
-    }
-
-    /**
-     * Class used to define a set of characters for matching purposes.
-     */
-    static final class StringMatcher extends StrMatcher {
-        /** The string to match, as a character array. */
-        private final char[] chars;
-
-        /**
-         * Constructor that creates a matcher from a String.
-         *
-         * @param str  the string to match, must not be null
-         */
-        StringMatcher(final String str) {
-            chars = str.toCharArray();
-        }
-
-        /**
-         * Returns the number of matching characters, or zero if there is no match.
-         *
-         * @param buffer  the text content to match against, do not change
-         * @param pos  the starting position for the match, valid for buffer
-         * @param bufferStart  the first active index in the buffer, valid for buffer
-         * @param bufferEnd  the end index of the active buffer, valid for buffer
-         * @return The number of matching characters, or zero if there is no match
-         */
-        @Override
-        public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
-            final int len = chars.length;
-            if (pos + len > bufferEnd) {
-                return 0;
-            }
-            for (int i = 0; i < chars.length; i++, pos++) {
-                if (chars[i] != buffer[pos]) {
-                    return 0;
-                }
-            }
-            return len;
-        }
-
-        @Override
-        public String toString() {
-            return super.toString() + ' ' + Arrays.toString(chars);
-        }
-
-    }
-
-    /**
-     * Class used to match no characters.
-     */
-    static final class NoMatcher extends StrMatcher {
-
-        /**
-         * Constructs a new instance of {@code NoMatcher}.
-         */
-        NoMatcher() {
-        }
-
-        /**
-         * Always returns {@code 0}.
-         *
-         * @param buffer  the text content to match against, do not change
-         * @param pos  the starting position for the match, valid for buffer
-         * @param bufferStart  the first active index in the buffer, valid for buffer
-         * @param bufferEnd  the end index of the active buffer, valid for buffer
-         * @return The number of matching characters, or zero if there is no match
-         */
-        @Override
-        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
-            return 0;
-        }
-    }
-
-    /**
-     * Class used to match whitespace as per trim().
-     */
-    static final class TrimMatcher extends StrMatcher {
-
-        /**
-         * Constructs a new instance of {@code TrimMatcher}.
-         */
-        TrimMatcher() {
-        }
-
-        /**
-         * Returns whether or not the given character matches.
-         *
-         * @param buffer  the text content to match against, do not change
-         * @param pos  the starting position for the match, valid for buffer
-         * @param bufferStart  the first active index in the buffer, valid for buffer
-         * @param bufferEnd  the end index of the active buffer, valid for buffer
-         * @return The number of matching characters, or zero if there is no match
-         */
-        @Override
-        public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
-            return buffer[pos] <= 32 ? 1 : 0;
-        }
-    }
+    public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd);
 
 }
diff --git a/src/main/java/org/apache/commons/text/StrSubstitutor.java b/src/main/java/org/apache/commons/text/StrSubstitutor.java
index 072401f..b15385d 100644
--- a/src/main/java/org/apache/commons/text/StrSubstitutor.java
+++ b/src/main/java/org/apache/commons/text/StrSubstitutor.java
@@ -147,46 +147,6 @@ public class StrSubstitutor {
     public static final StrMatcher DEFAULT_VALUE_DELIMITER = StrMatcher.stringMatcher(":-");
 
     /**
-     * Stores the escape character.
-     */
-    private char escapeChar;
-
-    /**
-     * Stores the variable prefix.
-     */
-    private StrMatcher prefixMatcher;
-
-    /**
-     * Stores the variable suffix.
-     */
-    private StrMatcher suffixMatcher;
-
-    /**
-     * Stores the default variable value delimiter.
-     */
-    private StrMatcher valueDelimiterMatcher;
-
-    /**
-     * Variable resolution is delegated to an implementor of VariableResolver.
-     */
-    private StrLookup<?> variableResolver;
-
-    /**
-     * The flag whether substitution in variable names is enabled.
-     */
-    private boolean enableSubstitutionInVariables;
-
-    /**
-     * Whether escapes should be preserved.  Default is false;
-     */
-    private boolean preserveEscapes;
-
-    /**
-     * The flag whether substitution in variable values is disabled.
-     */
-    private boolean disableSubstitutionInValues;
-
-    /**
      * Replaces all the occurrences of variables in the given source object with
      * their matching values from the map.
      *
@@ -253,6 +213,46 @@ public class StrSubstitutor {
     }
 
     /**
+     * Stores the escape character.
+     */
+    private char escapeChar;
+
+    /**
+     * Stores the variable prefix.
+     */
+    private StrMatcher prefixMatcher;
+
+    /**
+     * Stores the variable suffix.
+     */
+    private StrMatcher suffixMatcher;
+
+    /**
+     * Stores the default variable value delimiter.
+     */
+    private StrMatcher valueDelimiterMatcher;
+
+    /**
+     * Variable resolution is delegated to an implementor of VariableResolver.
+     */
+    private StrLookup<?> variableResolver;
+
+    /**
+     * The flag whether substitution in variable names is enabled.
+     */
+    private boolean enableSubstitutionInVariables;
+
+    /**
+     * Whether escapes should be preserved.  Default is false;
+     */
+    private boolean preserveEscapes;
+
+    /**
+     * The flag whether substitution in variable values is disabled.
+     */
+    private boolean disableSubstitutionInValues;
+
+    /**
      * Constructs a new instance with defaults for variable prefix and suffix
      * and the escaping character.
      */
@@ -397,45 +397,128 @@ public class StrSubstitutor {
     }
 
     /**
-     * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source string as a template.
+     * Checks if the specified variable is already in the stack (list) of variables.
      *
-     * @param source  the string to replace in, null returns null
-     * @return The result of the replace operation
+     * @param varName  the variable name to check
+     * @param priorVariables  the list of prior variables
      */
-    public String replace(final String source) {
-        if (source == null) {
-            return null;
-        }
-        final StrBuilder buf = new StrBuilder(source);
-        if (!substitute(buf, 0, source.length())) {
-            return source;
+    private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
+        if (!priorVariables.contains(varName)) {
+            return;
         }
-        return buf.toString();
+        final StrBuilder buf = new StrBuilder(256);
+        buf.append("Infinite loop in property interpolation of ");
+        buf.append(priorVariables.remove(0));
+        buf.append(": ");
+        buf.appendWithSeparators(priorVariables, "->");
+        throw new IllegalStateException(buf.toString());
     }
 
     /**
-     * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source string as a template.
+     * Returns the escape character.
+     *
+     * @return The character used for escaping variable references
+     */
+    public char getEscapeChar() {
+        return this.escapeChar;
+    }
+
+    /**
+     * Gets the variable default value delimiter matcher currently in use.
      * <p>
-     * Only the specified portion of the string will be processed.
-     * The rest of the string is not processed, and is not returned.
+     * The variable default value delimiter is the character or characters that delimit the
+     * variable name and the variable default value. This delimiter is expressed in terms of a matcher
+     * allowing advanced variable default value delimiter matches.
+     * </p>
+     * <p>
+     * If it returns null, then the variable default value resolution is disabled.
      * </p>
      *
-     * @param source  the string to replace in, null returns null
-     * @param offset  the start offset within the array, must be valid
-     * @param length  the length within the array to be processed, must be valid
-     * @return The result of the replace operation
+     * @return The variable default value delimiter matcher in use, may be null
      */
-    public String replace(final String source, final int offset, final int length) {
-        if (source == null) {
-            return null;
-        }
-        final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
-        if (!substitute(buf, 0, length)) {
-            return source.substring(offset, offset + length);
-        }
-        return buf.toString();
+    public StrMatcher getValueDelimiterMatcher() {
+        return valueDelimiterMatcher;
+    }
+
+    /**
+     * Gets the variable prefix matcher currently in use.
+     * <p>
+     * The variable prefix is the character or characters that identify the
+     * start of a variable. This prefix is expressed in terms of a matcher
+     * allowing advanced prefix matches.
+     * </p>
+     *
+     * @return The prefix matcher in use
+     */
+    public StrMatcher getVariablePrefixMatcher() {
+        return prefixMatcher;
+    }
+
+    /**
+     * Gets the VariableResolver that is used to lookup variables.
+     *
+     * @return The VariableResolver
+     */
+    public StrLookup<?> getVariableResolver() {
+        return this.variableResolver;
+    }
+
+    /**
+     * Gets the variable suffix matcher currently in use.
+     * <p>
+     * The variable suffix is the character or characters that identify the
+     * end of a variable. This suffix is expressed in terms of a matcher
+     * allowing advanced suffix matches.
+     * </p>
+     *
+     * @return The suffix matcher in use
+     */
+    public StrMatcher getVariableSuffixMatcher() {
+        return suffixMatcher;
+    }
+
+    /**
+     * Returns a flag whether substitution is disabled in variable values.If set to
+     * <b>true</b>, the values of variables can contain other variables will not be
+     * processed and substituted original variable is evaluated, e.g.
+     * <pre>
+     * Map&lt;String, String&gt; valuesMap = new HashMap&lt;&gt;();
+     * valuesMap.put(&quot;name&quot;, &quot;Douglas ${surname}&quot;);
+     * valuesMap.put(&quot;surname&quot;, &quot;Crockford&quot;);
+     * String templateString = &quot;Hi ${name}&quot;;
+     * StrSubstitutor sub = new StrSubstitutor(valuesMap);
+     * String resolvedString = sub.replace(templateString);
+     * </pre>
+     * yielding:
+     * <pre>
+     *      Hi Douglas ${surname}
+     * </pre>
+     *
+     * @return The substitution in variable values flag
+     *
+     * @since 1.2
+     */
+    public boolean isDisableSubstitutionInValues() {
+        return disableSubstitutionInValues;
+    }
+
+    /**
+     * Returns a flag whether substitution is done in variable names.
+     *
+     * @return The substitution in variable names flag
+     */
+    public boolean isEnableSubstitutionInVariables() {
+        return enableSubstitutionInVariables;
+    }
+
+    /**
+     * Returns the flag controlling whether escapes are preserved during
+     * substitution.
+     *
+     * @return The preserve escape flag
+     */
+    public boolean isPreserveEscapes() {
+        return preserveEscapes;
     }
 
     /**
@@ -480,25 +563,23 @@ public class StrSubstitutor {
 
     /**
      * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source buffer as a template.
-     * The buffer is not altered by this method.
+     * from the resolver using the given source as a template.
+     * The source is not altered by this method.
      *
      * @param source  the buffer to use as a template, not changed, null returns null
      * @return The result of the replace operation
      */
-    public String replace(final StringBuffer source) {
+    public String replace(final CharSequence source) {
         if (source == null) {
             return null;
         }
-        final StrBuilder buf = new StrBuilder(source.length()).append(source);
-        substitute(buf, 0, buf.length());
-        return buf.toString();
+        return replace(source, 0, source.length());
     }
 
     /**
      * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source buffer as a template.
-     * The buffer is not altered by this method.
+     * from the resolver using the given source as a template.
+     * The source is not altered by this method.
      * <p>
      * Only the specified portion of the buffer will be processed.
      * The rest of the buffer is not processed, and is not returned.
@@ -509,7 +590,7 @@ public class StrSubstitutor {
      * @param length  the length within the array to be processed, must be valid
      * @return The result of the replace operation
      */
-    public String replace(final StringBuffer source, final int offset, final int length) {
+    public String replace(final CharSequence source, final int offset, final int length) {
         if (source == null) {
             return null;
         }
@@ -519,35 +600,54 @@ public class StrSubstitutor {
     }
 
     /**
-     * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source as a template.
-     * The source is not altered by this method.
+     * Replaces all the occurrences of variables in the given source object with
+     * their matching values from the resolver. The input source object is
+     * converted to a string using {@code toString} and is not altered.
      *
-     * @param source  the buffer to use as a template, not changed, null returns null
+     * @param source  the source to replace in, null returns null
      * @return The result of the replace operation
      */
-    public String replace(final CharSequence source) {
+    public String replace(final Object source) {
         if (source == null) {
             return null;
         }
-        return replace(source, 0, source.length());
+        final StrBuilder buf = new StrBuilder().append(source);
+        substitute(buf, 0, buf.length());
+        return buf.toString();
     }
 
     /**
      * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source as a template.
-     * The source is not altered by this method.
-     * <p>
-     * Only the specified portion of the buffer will be processed.
-     * The rest of the buffer is not processed, and is not returned.
+     * from the resolver using the given source builder as a template.
+     * The builder is not altered by this method.
+     *
+     * @param source  the builder to use as a template, not changed, null returns null
+     * @return The result of the replace operation
+     */
+    public String replace(final StrBuilder source) {
+        if (source == null) {
+            return null;
+        }
+        final StrBuilder buf = new StrBuilder(source.length()).append(source);
+        substitute(buf, 0, buf.length());
+        return buf.toString();
+    }
+
+    /**
+     * Replaces all the occurrences of variables with their matching values
+     * from the resolver using the given source builder as a template.
+     * The builder is not altered by this method.
+     * <p>
+     * Only the specified portion of the builder will be processed.
+     * The rest of the builder is not processed, and is not returned.
      * </p>
      *
-     * @param source  the buffer to use as a template, not changed, null returns null
+     * @param source  the builder to use as a template, not changed, null returns null
      * @param offset  the start offset within the array, must be valid
      * @param length  the length within the array to be processed, must be valid
      * @return The result of the replace operation
      */
-    public String replace(final CharSequence source, final int offset, final int length) {
+    public String replace(final StrBuilder source, final int offset, final int length) {
         if (source == null) {
             return null;
         }
@@ -558,62 +658,121 @@ public class StrSubstitutor {
 
     /**
      * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source builder as a template.
-     * The builder is not altered by this method.
+     * from the resolver using the given source string as a template.
      *
-     * @param source  the builder to use as a template, not changed, null returns null
+     * @param source  the string to replace in, null returns null
      * @return The result of the replace operation
      */
-    public String replace(final StrBuilder source) {
+    public String replace(final String source) {
         if (source == null) {
             return null;
         }
-        final StrBuilder buf = new StrBuilder(source.length()).append(source);
-        substitute(buf, 0, buf.length());
+        final StrBuilder buf = new StrBuilder(source);
+        if (!substitute(buf, 0, source.length())) {
+            return source;
+        }
         return buf.toString();
     }
 
     /**
      * Replaces all the occurrences of variables with their matching values
-     * from the resolver using the given source builder as a template.
-     * The builder is not altered by this method.
+     * from the resolver using the given source string as a template.
      * <p>
-     * Only the specified portion of the builder will be processed.
-     * The rest of the builder is not processed, and is not returned.
+     * Only the specified portion of the string will be processed.
+     * The rest of the string is not processed, and is not returned.
      * </p>
      *
-     * @param source  the builder to use as a template, not changed, null returns null
+     * @param source  the string to replace in, null returns null
      * @param offset  the start offset within the array, must be valid
      * @param length  the length within the array to be processed, must be valid
      * @return The result of the replace operation
      */
-    public String replace(final StrBuilder source, final int offset, final int length) {
+    public String replace(final String source, final int offset, final int length) {
         if (source == null) {
             return null;
         }
         final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
-        substitute(buf, 0, length);
+        if (!substitute(buf, 0, length)) {
+            return source.substring(offset, offset + length);
+        }
         return buf.toString();
     }
 
     /**
-     * Replaces all the occurrences of variables in the given source object with
-     * their matching values from the resolver. The input source object is
-     * converted to a string using {@code toString} and is not altered.
+     * Replaces all the occurrences of variables with their matching values
+     * from the resolver using the given source buffer as a template.
+     * The buffer is not altered by this method.
      *
-     * @param source  the source to replace in, null returns null
+     * @param source  the buffer to use as a template, not changed, null returns null
      * @return The result of the replace operation
      */
-    public String replace(final Object source) {
+    public String replace(final StringBuffer source) {
         if (source == null) {
             return null;
         }
-        final StrBuilder buf = new StrBuilder().append(source);
+        final StrBuilder buf = new StrBuilder(source.length()).append(source);
         substitute(buf, 0, buf.length());
         return buf.toString();
     }
 
     /**
+     * Replaces all the occurrences of variables with their matching values
+     * from the resolver using the given source buffer as a template.
+     * The buffer is not altered by this method.
+     * <p>
+     * Only the specified portion of the buffer will be processed.
+     * The rest of the buffer is not processed, and is not returned.
+     * </p>
+     *
+     * @param source  the buffer to use as a template, not changed, null returns null
+     * @param offset  the start offset within the array, must be valid
+     * @param length  the length within the array to be processed, must be valid
+     * @return The result of the replace operation
+     */
+    public String replace(final StringBuffer source, final int offset, final int length) {
+        if (source == null) {
+            return null;
+        }
+        final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+        substitute(buf, 0, length);
+        return buf.toString();
+    }
+
+    /**
+     * Replaces all the occurrences of variables within the given source
+     * builder with their matching values from the resolver.
+     *
+     * @param source  the builder to replace in, updated, null returns zero
+     * @return true if altered
+     */
+    public boolean replaceIn(final StrBuilder source) {
+        if (source == null) {
+            return false;
+        }
+        return substitute(source, 0, source.length());
+    }
+
+    /**
+     * Replaces all the occurrences of variables within the given source
+     * builder with their matching values from the resolver.
+     * <p>
+     * Only the specified portion of the builder will be processed.
+     * The rest of the builder is not processed, but it is not deleted.
+     * </p>
+     *
+     * @param source  the builder to replace in, null returns zero
+     * @param offset  the start offset within the array, must be valid
+     * @param length  the length within the builder to be processed, must be valid
+     * @return true if altered
+     */
+    public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
+        if (source == null) {
+            return false;
+        }
+        return substitute(source, offset, length);
+    }
+
+    /**
      * Replaces all the occurrences of variables within the given source buffer
      * with their matching values from the resolver.
      * The buffer is updated with the result.
@@ -696,65 +855,276 @@ public class StrSubstitutor {
     }
 
     /**
-     * Replaces all the occurrences of variables within the given source
-     * builder with their matching values from the resolver.
+     * Internal method that resolves the value of a variable.
+     * <p>
+     * Most users of this class do not need to call this method. This method is
+     * called automatically by the substitution process.
+     * </p>
+     * <p>
+     * Writers of subclasses can override this method if they need to alter
+     * how each substitution occurs. The method is passed the variable's name
+     * and must return the corresponding value. This implementation uses the
+     * {@link #getVariableResolver()} with the variable's name as the key.
+     * </p>
      *
-     * @param source  the builder to replace in, updated, null returns zero
-     * @return true if altered
+     * @param variableName  the name of the variable, not null
+     * @param buf  the buffer where the substitution is occurring, not null
+     * @param startPos  the start position of the variable including the prefix, valid
+     * @param endPos  the end position of the variable including the suffix, valid
+     * @return The variable's value or <b>null</b> if the variable is unknown
      */
-    public boolean replaceIn(final StrBuilder source) {
-        if (source == null) {
-            return false;
+    protected String resolveVariable(final String variableName,
+                                     final StrBuilder buf,
+                                     final int startPos,
+                                     final int endPos) {
+        final StrLookup<?> resolver = getVariableResolver();
+        if (resolver == null) {
+            return null;
         }
-        return substitute(source, 0, source.length());
+        return resolver.lookup(variableName);
     }
 
     /**
-     * Replaces all the occurrences of variables within the given source
-     * builder with their matching values from the resolver.
+     * Sets a flag whether substitution is done in variable values (recursive).
+     *
+     * @param disableSubstitutionInValues true if substitution in variable value are disabled
+     *
+     * @since 1.2
+     */
+    public void setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
+        this.disableSubstitutionInValues = disableSubstitutionInValues;
+    }
+
+    /**
+     * Sets a flag whether substitution is done in variable names. If set to
+     * <b>true</b>, the names of variables can contain other variables which are
+     * processed first before the original variable is evaluated, e.g.
+     * {@code ${jre-${java.version}}}. The default value is <b>false</b>.
+     *
+     * @param enableSubstitutionInVariables the new value of the flag
+     */
+    public void setEnableSubstitutionInVariables(
+            final boolean enableSubstitutionInVariables) {
+        this.enableSubstitutionInVariables = enableSubstitutionInVariables;
+    }
+
+    /**
+     * Sets the escape character.
+     * If this character is placed before a variable reference in the source
+     * text, this variable will be ignored.
+     *
+     * @param escapeCharacter  the escape character (0 for disabling escaping)
+     */
+    public void setEscapeChar(final char escapeCharacter) {
+        this.escapeChar = escapeCharacter;
+    }
+
+    /**
+     * Sets a flag controlling whether escapes are preserved during
+     * substitution.  If set to <b>true</b>, the escape character is retained
+     * during substitution (e.g. {@code $${this-is-escaped}} remains
+     * {@code $${this-is-escaped}}).  If set to <b>false</b>, the escape
+     * character is removed during substitution (e.g.
+     * {@code $${this-is-escaped}} becomes
+     * {@code ${this-is-escaped}}).  The default value is <b>false</b>
+     *
+     * @param preserveEscapes true if escapes are to be preserved
+     */
+    public void setPreserveEscapes(final boolean preserveEscapes) {
+        this.preserveEscapes = preserveEscapes;
+    }
+
+    /**
+     * Sets the variable default value delimiter to use.
      * <p>
-     * Only the specified portion of the builder will be processed.
-     * The rest of the builder is not processed, but it is not deleted.
+     * The variable default value delimiter is the character or characters that delimit the
+     * variable name and the variable default value. This method allows a single character
+     * variable default value delimiter to be easily set.
      * </p>
      *
-     * @param source  the builder to replace in, null returns zero
-     * @param offset  the start offset within the array, must be valid
-     * @param length  the length within the builder to be processed, must be valid
-     * @return true if altered
+     * @param valueDelimiter  the variable default value delimiter character to use
+     * @return this, to enable chaining
      */
-    public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
-        if (source == null) {
-            return false;
-        }
-        return substitute(source, offset, length);
+    public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
+        return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
     }
 
     /**
-     * Internal method that substitutes the variables.
+     * Sets the variable default value delimiter to use.
      * <p>
-     * Most users of this class do not need to call this method. This method will
-     * be called automatically by another (public) method.
+     * The variable default value delimiter is the character or characters that delimit the
+     * variable name and the variable default value. This method allows a string
+     * variable default value delimiter to be easily set.
      * </p>
      * <p>
-     * Writers of subclasses can override this method if they need access to
-     * the substitution process at the start or end.
+     * If the {@code valueDelimiter} is null or empty string, then the variable default
+     * value resolution becomes disabled.
      * </p>
      *
-     * @param buf  the string builder to substitute into, not null
-     * @param offset  the start offset within the builder, must be valid
-     * @param length  the length within the builder to be processed, must be valid
-     * @return true if altered
+     * @param valueDelimiter  the variable default value delimiter string to use, may be null or empty
+     * @return this, to enable chaining
      */
-    protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
-        return substitute(buf, offset, length, null) > 0;
+    public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
+        if (valueDelimiter == null || valueDelimiter.isEmpty()) {
+            setValueDelimiterMatcher(null);
+            return this;
+        }
+        return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter));
     }
 
     /**
-     * Recursive handler for multiple levels of interpolation. This is the main
-     * interpolation method, which resolves the values of all variable references
-     * contained in the passed in text.
-     *
-     * @param buf  the string builder to substitute into, not null
+     * Sets the variable default value delimiter matcher to use.
+     * <p>
+     * The variable default value delimiter is the character or characters that delimit the
+     * variable name and the variable default value. This delimiter is expressed in terms of a matcher
+     * allowing advanced variable default value delimiter matches.
+     * </p>
+     * <p>
+     * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution
+     * becomes disabled.
+     * </p>
+     *
+     * @param valueDelimiterMatcher  variable default value delimiter matcher to use, may be null
+     * @return this, to enable chaining
+     */
+    public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
+        this.valueDelimiterMatcher = valueDelimiterMatcher;
+        return this;
+    }
+
+    /**
+     * Sets the variable prefix to use.
+     * <p>
+     * The variable prefix is the character or characters that identify the
+     * start of a variable. This method allows a single character prefix to
+     * be easily set.
+     * </p>
+     *
+     * @param prefix  the prefix character to use
+     * @return this, to enable chaining
+     */
+    public StrSubstitutor setVariablePrefix(final char prefix) {
+        return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
+    }
+
+    /**
+     * Sets the variable prefix to use.
+     * <p>
+     * The variable prefix is the character or characters that identify the
+     * start of a variable. This method allows a string prefix to be easily set.
+     * </p>
+     *
+     * @param prefix  the prefix for variables, not null
+     * @return this, to enable chaining
+     * @throws IllegalArgumentException if the prefix is null
+     */
+    public StrSubstitutor setVariablePrefix(final String prefix) {
+        Validate.isTrue(prefix != null, "Variable prefix must not be null!");
+        return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix));
+    }
+
+    /**
+     * Sets the variable prefix matcher currently in use.
+     * <p>
+     * The variable prefix is the character or characters that identify the
+     * start of a variable. This prefix is expressed in terms of a matcher
+     * allowing advanced prefix matches.
+     * </p>
+     *
+     * @param prefixMatcher  the prefix matcher to use, null ignored
+     * @return this, to enable chaining
+     * @throws IllegalArgumentException if the prefix matcher is null
+     */
+    public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
+        Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
+        this.prefixMatcher = prefixMatcher;
+        return this;
+    }
+
+    /**
+     * Sets the VariableResolver that is used to lookup variables.
+     *
+     * @param variableResolver  the VariableResolver
+     */
+    public void setVariableResolver(final StrLookup<?> variableResolver) {
+        this.variableResolver = variableResolver;
+    }
+
+    /**
+     * Sets the variable suffix to use.
+     * <p>
+     * The variable suffix is the character or characters that identify the
+     * end of a variable. This method allows a single character suffix to
+     * be easily set.
+     * </p>
+     *
+     * @param suffix  the suffix character to use
+     * @return this, to enable chaining
+     */
+    public StrSubstitutor setVariableSuffix(final char suffix) {
+        return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
+    }
+
+    /**
+     * Sets the variable suffix to use.
+     * <p>
+     * The variable suffix is the character or characters that identify the
+     * end of a variable. This method allows a string suffix to be easily set.
+     * </p>
+     *
+     * @param suffix  the suffix for variables, not null
+     * @return this, to enable chaining
+     * @throws IllegalArgumentException if the suffix is null
+     */
+    public StrSubstitutor setVariableSuffix(final String suffix) {
+        Validate.isTrue(suffix != null, "Variable suffix must not be null!");
+        return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
+    }
+
+    /**
+     * Sets the variable suffix matcher currently in use.
+     * <p>
+     * The variable suffix is the character or characters that identify the
+     * end of a variable. This suffix is expressed in terms of a matcher
+     * allowing advanced suffix matches.
+     * </p>
+     *
+     * @param suffixMatcher  the suffix matcher to use, null ignored
+     * @return this, to enable chaining
+     * @throws IllegalArgumentException if the suffix matcher is null
+     */
+    public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
+        Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
+        this.suffixMatcher = suffixMatcher;
+        return this;
+    }
+
+    /**
+     * Internal method that substitutes the variables.
+     * <p>
+     * Most users of this class do not need to call this method. This method will
+     * be called automatically by another (public) method.
+     * </p>
+     * <p>
+     * Writers of subclasses can override this method if they need access to
+     * the substitution process at the start or end.
+     * </p>
+     *
+     * @param buf  the string builder to substitute into, not null
+     * @param offset  the start offset within the builder, must be valid
+     * @param length  the length within the builder to be processed, must be valid
+     * @return true if altered
+     */
+    protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
+        return substitute(buf, offset, length, null) > 0;
+    }
+
+    /**
+     * Recursive handler for multiple levels of interpolation. This is the main
+     * interpolation method, which resolves the values of all variable references
+     * contained in the passed in text.
+     *
+     * @param buf  the string builder to substitute into, not null
      * @param offset  the start offset within the builder, must be valid
      * @param length  the length within the builder to be processed, must be valid
      * @param priorVariables  the stack keeping track of the replaced variables, may be null
@@ -906,374 +1276,4 @@ public class StrSubstitutor {
         }
         return lengthChange;
     }
-
-    /**
-     * Checks if the specified variable is already in the stack (list) of variables.
-     *
-     * @param varName  the variable name to check
-     * @param priorVariables  the list of prior variables
-     */
-    private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
-        if (!priorVariables.contains(varName)) {
-            return;
-        }
-        final StrBuilder buf = new StrBuilder(256);
-        buf.append("Infinite loop in property interpolation of ");
-        buf.append(priorVariables.remove(0));
-        buf.append(": ");
-        buf.appendWithSeparators(priorVariables, "->");
-        throw new IllegalStateException(buf.toString());
-    }
-
-    /**
-     * Internal method that resolves the value of a variable.
-     * <p>
-     * Most users of this class do not need to call this method. This method is
-     * called automatically by the substitution process.
-     * </p>
-     * <p>
-     * Writers of subclasses can override this method if they need to alter
-     * how each substitution occurs. The method is passed the variable's name
-     * and must return the corresponding value. This implementation uses the
-     * {@link #getVariableResolver()} with the variable's name as the key.
-     * </p>
-     *
-     * @param variableName  the name of the variable, not null
-     * @param buf  the buffer where the substitution is occurring, not null
-     * @param startPos  the start position of the variable including the prefix, valid
-     * @param endPos  the end position of the variable including the suffix, valid
-     * @return The variable's value or <b>null</b> if the variable is unknown
-     */
-    protected String resolveVariable(final String variableName,
-                                     final StrBuilder buf,
-                                     final int startPos,
-                                     final int endPos) {
-        final StrLookup<?> resolver = getVariableResolver();
-        if (resolver == null) {
-            return null;
-        }
-        return resolver.lookup(variableName);
-    }
-
-    /**
-     * Returns the escape character.
-     *
-     * @return The character used for escaping variable references
-     */
-    public char getEscapeChar() {
-        return this.escapeChar;
-    }
-
-    /**
-     * Sets the escape character.
-     * If this character is placed before a variable reference in the source
-     * text, this variable will be ignored.
-     *
-     * @param escapeCharacter  the escape character (0 for disabling escaping)
-     */
-    public void setEscapeChar(final char escapeCharacter) {
-        this.escapeChar = escapeCharacter;
-    }
-
-    /**
-     * Gets the variable prefix matcher currently in use.
-     * <p>
-     * The variable prefix is the character or characters that identify the
-     * start of a variable. This prefix is expressed in terms of a matcher
-     * allowing advanced prefix matches.
-     * </p>
-     *
-     * @return The prefix matcher in use
-     */
-    public StrMatcher getVariablePrefixMatcher() {
-        return prefixMatcher;
-    }
-
-    /**
-     * Sets the variable prefix matcher currently in use.
-     * <p>
-     * The variable prefix is the character or characters that identify the
-     * start of a variable. This prefix is expressed in terms of a matcher
-     * allowing advanced prefix matches.
-     * </p>
-     *
-     * @param prefixMatcher  the prefix matcher to use, null ignored
-     * @return this, to enable chaining
-     * @throws IllegalArgumentException if the prefix matcher is null
-     */
-    public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
-        Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
-        this.prefixMatcher = prefixMatcher;
-        return this;
-    }
-
-    /**
-     * Sets the variable prefix to use.
-     * <p>
-     * The variable prefix is the character or characters that identify the
-     * start of a variable. This method allows a single character prefix to
-     * be easily set.
-     * </p>
-     *
-     * @param prefix  the prefix character to use
-     * @return this, to enable chaining
-     */
-    public StrSubstitutor setVariablePrefix(final char prefix) {
-        return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
-    }
-
-    /**
-     * Sets the variable prefix to use.
-     * <p>
-     * The variable prefix is the character or characters that identify the
-     * start of a variable. This method allows a string prefix to be easily set.
-     * </p>
-     *
-     * @param prefix  the prefix for variables, not null
-     * @return this, to enable chaining
-     * @throws IllegalArgumentException if the prefix is null
-     */
-    public StrSubstitutor setVariablePrefix(final String prefix) {
-        Validate.isTrue(prefix != null, "Variable prefix must not be null!");
-        return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix));
-    }
-
-    /**
-     * Gets the variable suffix matcher currently in use.
-     * <p>
-     * The variable suffix is the character or characters that identify the
-     * end of a variable. This suffix is expressed in terms of a matcher
-     * allowing advanced suffix matches.
-     * </p>
-     *
-     * @return The suffix matcher in use
-     */
-    public StrMatcher getVariableSuffixMatcher() {
-        return suffixMatcher;
-    }
-
-    /**
-     * Sets the variable suffix matcher currently in use.
-     * <p>
-     * The variable suffix is the character or characters that identify the
-     * end of a variable. This suffix is expressed in terms of a matcher
-     * allowing advanced suffix matches.
-     * </p>
-     *
-     * @param suffixMatcher  the suffix matcher to use, null ignored
-     * @return this, to enable chaining
-     * @throws IllegalArgumentException if the suffix matcher is null
-     */
-    public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
-        Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
-        this.suffixMatcher = suffixMatcher;
-        return this;
-    }
-
-    /**
-     * Sets the variable suffix to use.
-     * <p>
-     * The variable suffix is the character or characters that identify the
-     * end of a variable. This method allows a single character suffix to
-     * be easily set.
-     * </p>
-     *
-     * @param suffix  the suffix character to use
-     * @return this, to enable chaining
-     */
-    public StrSubstitutor setVariableSuffix(final char suffix) {
-        return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
-    }
-
-    /**
-     * Sets the variable suffix to use.
-     * <p>
-     * The variable suffix is the character or characters that identify the
-     * end of a variable. This method allows a string suffix to be easily set.
-     * </p>
-     *
-     * @param suffix  the suffix for variables, not null
-     * @return this, to enable chaining
-     * @throws IllegalArgumentException if the suffix is null
-     */
-    public StrSubstitutor setVariableSuffix(final String suffix) {
-        Validate.isTrue(suffix != null, "Variable suffix must not be null!");
-        return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
-    }
-
-    /**
-     * Gets the variable default value delimiter matcher currently in use.
-     * <p>
-     * The variable default value delimiter is the character or characters that delimit the
-     * variable name and the variable default value. This delimiter is expressed in terms of a matcher
-     * allowing advanced variable default value delimiter matches.
-     * </p>
-     * <p>
-     * If it returns null, then the variable default value resolution is disabled.
-     * </p>
-     *
-     * @return The variable default value delimiter matcher in use, may be null
-     */
-    public StrMatcher getValueDelimiterMatcher() {
-        return valueDelimiterMatcher;
-    }
-
-    /**
-     * Sets the variable default value delimiter matcher to use.
-     * <p>
-     * The variable default value delimiter is the character or characters that delimit the
-     * variable name and the variable default value. This delimiter is expressed in terms of a matcher
-     * allowing advanced variable default value delimiter matches.
-     * </p>
-     * <p>
-     * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution
-     * becomes disabled.
-     * </p>
-     *
-     * @param valueDelimiterMatcher  variable default value delimiter matcher to use, may be null
-     * @return this, to enable chaining
-     */
-    public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
-        this.valueDelimiterMatcher = valueDelimiterMatcher;
-        return this;
-    }
-
-    /**
-     * Sets the variable default value delimiter to use.
-     * <p>
-     * The variable default value delimiter is the character or characters that delimit the
-     * variable name and the variable default value. This method allows a single character
-     * variable default value delimiter to be easily set.
-     * </p>
-     *
-     * @param valueDelimiter  the variable default value delimiter character to use
-     * @return this, to enable chaining
-     */
-    public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
-        return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
-    }
-
-    /**
-     * Sets the variable default value delimiter to use.
-     * <p>
-     * The variable default value delimiter is the character or characters that delimit the
-     * variable name and the variable default value. This method allows a string
-     * variable default value delimiter to be easily set.
-     * </p>
-     * <p>
-     * If the {@code valueDelimiter} is null or empty string, then the variable default
-     * value resolution becomes disabled.
-     * </p>
-     *
-     * @param valueDelimiter  the variable default value delimiter string to use, may be null or empty
-     * @return this, to enable chaining
-     */
-    public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
-        if (valueDelimiter == null || valueDelimiter.isEmpty()) {
-            setValueDelimiterMatcher(null);
-            return this;
-        }
-        return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter));
-    }
-
-    /**
-     * Gets the VariableResolver that is used to lookup variables.
-     *
-     * @return The VariableResolver
-     */
-    public StrLookup<?> getVariableResolver() {
-        return this.variableResolver;
-    }
-
-    /**
-     * Sets the VariableResolver that is used to lookup variables.
-     *
-     * @param variableResolver  the VariableResolver
-     */
-    public void setVariableResolver(final StrLookup<?> variableResolver) {
-        this.variableResolver = variableResolver;
-    }
-
-    /**
-     * Returns a flag whether substitution is done in variable names.
-     *
-     * @return The substitution in variable names flag
-     */
-    public boolean isEnableSubstitutionInVariables() {
-        return enableSubstitutionInVariables;
-    }
-
-    /**
-     * Sets a flag whether substitution is done in variable names. If set to
-     * <b>true</b>, the names of variables can contain other variables which are
-     * processed first before the original variable is evaluated, e.g.
-     * {@code ${jre-${java.version}}}. The default value is <b>false</b>.
-     *
-     * @param enableSubstitutionInVariables the new value of the flag
-     */
-    public void setEnableSubstitutionInVariables(
-            final boolean enableSubstitutionInVariables) {
-        this.enableSubstitutionInVariables = enableSubstitutionInVariables;
-    }
-
-    /**
-     * Returns a flag whether substitution is disabled in variable values.If set to
-     * <b>true</b>, the values of variables can contain other variables will not be
-     * processed and substituted original variable is evaluated, e.g.
-     * <pre>
-     * Map&lt;String, String&gt; valuesMap = new HashMap&lt;&gt;();
-     * valuesMap.put(&quot;name&quot;, &quot;Douglas ${surname}&quot;);
-     * valuesMap.put(&quot;surname&quot;, &quot;Crockford&quot;);
-     * String templateString = &quot;Hi ${name}&quot;;
-     * StrSubstitutor sub = new StrSubstitutor(valuesMap);
-     * String resolvedString = sub.replace(templateString);
-     * </pre>
-     * yielding:
-     * <pre>
-     *      Hi Douglas ${surname}
-     * </pre>
-     *
-     * @return The substitution in variable values flag
-     *
-     * @since 1.2
-     */
-    public boolean isDisableSubstitutionInValues() {
-        return disableSubstitutionInValues;
-    }
-
-    /**
-     * Sets a flag whether substitution is done in variable values (recursive).
-     *
-     * @param disableSubstitutionInValues true if substitution in variable value are disabled
-     *
-     * @since 1.2
-     */
-    public void setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
-        this.disableSubstitutionInValues = disableSubstitutionInValues;
-    }
-
-    /**
-     * Returns the flag controlling whether escapes are preserved during
-     * substitution.
-     *
-     * @return The preserve escape flag
-     */
-    public boolean isPreserveEscapes() {
-        return preserveEscapes;
-    }
-
-    /**
-     * Sets a flag controlling whether escapes are preserved during
-     * substitution.  If set to <b>true</b>, the escape character is retained
-     * during substitution (e.g. {@code $${this-is-escaped}} remains
-     * {@code $${this-is-escaped}}).  If set to <b>false</b>, the escape
-     * character is removed during substitution (e.g.
-     * {@code $${this-is-escaped}} becomes
-     * {@code ${this-is-escaped}}).  The default value is <b>false</b>
-     *
-     * @param preserveEscapes true if escapes are to be preserved
-     */
-    public void setPreserveEscapes(final boolean preserveEscapes) {
-        this.preserveEscapes = preserveEscapes;
-    }
 }
diff --git a/src/main/java/org/apache/commons/text/StringEscapeUtils.java b/src/main/java/org/apache/commons/text/StringEscapeUtils.java
index 786915d..0c61628 100644
--- a/src/main/java/org/apache/commons/text/StringEscapeUtils.java
+++ b/src/main/java/org/apache/commons/text/StringEscapeUtils.java
@@ -55,6 +55,115 @@ public class StringEscapeUtils {
     /* ESCAPE TRANSLATORS */
 
     /**
+     * Convenience wrapper for {@link java.lang.StringBuilder} providing escape methods.
+     *
+     * <p>Example:</p>
+     * <pre>
+     * new Builder(ESCAPE_HTML4)
+     *      .append("&lt;p&gt;")
+     *      .escape("This is paragraph 1 and special chars like &amp; get escaped.")
+     *      .append("&lt;/p&gt;&lt;p&gt;")
+     *      .escape("This is paragraph 2 &amp; more...")
+     *      .append("&lt;/p&gt;")
+     *      .toString()
+     * </pre>
+     *
+     */
+    public static final class Builder {
+
+        /**
+         * StringBuilder to be used in the Builder class.
+         */
+        private final StringBuilder sb;
+
+        /**
+         * CharSequenceTranslator to be used in the Builder class.
+         */
+        private final CharSequenceTranslator translator;
+
+        /**
+         * Builder constructor.
+         *
+         * @param translator a CharSequenceTranslator.
+         */
+        private Builder(final CharSequenceTranslator translator) {
+            this.sb = new StringBuilder();
+            this.translator = translator;
+        }
+
+        /**
+         * Literal append, no escaping being done.
+         *
+         * @param input the String to append
+         * @return {@code this}, to enable chaining
+         */
+        public Builder append(final String input) {
+            sb.append(input);
+            return this;
+        }
+
+        /**
+         * Escape {@code input} according to the given {@link CharSequenceTranslator}.
+         *
+         * @param input the String to escape
+         * @return {@code this}, to enable chaining
+         */
+        public Builder escape(final String input) {
+            sb.append(translator.translate(input));
+            return this;
+        }
+
+        /**
+         * Return the escaped string.
+         *
+         * @return The escaped string
+         */
+        @Override
+        public String toString() {
+            return sb.toString();
+        }
+    }
+    /**
+     * Translator object for unescaping backslash escaped entries.
+     */
+    static class XsiUnescaper extends CharSequenceTranslator {
+
+        /**
+         * Escaped backslash constant.
+         */
+        private static final char BACKSLASH = '\\';
+
+        @Override
+        public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
+
+            if (index != 0) {
+                throw new IllegalStateException("XsiUnescaper should never reach the [1] index");
+            }
+
+            final String s = input.toString();
+
+            int segmentStart = 0;
+            int searchOffset = 0;
+            while (true) {
+                final int pos = s.indexOf(BACKSLASH, searchOffset);
+                if (pos == -1) {
+                    if (segmentStart < s.length()) {
+                        writer.write(s.substring(segmentStart));
+                    }
+                    break;
+                }
+                if (pos > segmentStart) {
+                    writer.write(s.substring(segmentStart, pos));
+                }
+                segmentStart = pos + 1;
+                searchOffset = pos + 2;
+            }
+
+            return Character.codePointCount(input, 0, input.length());
+        }
+    }
+
+    /**
      * Translator object for escaping Java.
      *
      * While {@link #escapeJava(String)} is the expected method of use, this
@@ -173,6 +282,7 @@ public class StringEscapeUtils {
      * as the foundation for a custom translator.
      */
     public static final CharSequenceTranslator ESCAPE_XML11;
+
     static {
         final Map<CharSequence, CharSequence> escapeXml11Map = new HashMap<>();
         escapeXml11Map.put("\u0000", StringUtils.EMPTY);
@@ -218,7 +328,6 @@ public class StringEscapeUtils {
                     new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE),
                     new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE)
             );
-
     /**
      * Translator object for escaping individual Comma Separated Values.
      *
@@ -228,6 +337,8 @@ public class StringEscapeUtils {
      */
     public static final CharSequenceTranslator ESCAPE_CSV = new CsvTranslators.CsvEscaper();
 
+    /* UNESCAPE TRANSLATORS */
+
     /**
      * Translator object for escaping Shell command language.
      *
@@ -264,8 +375,6 @@ public class StringEscapeUtils {
         );
     }
 
-    /* UNESCAPE TRANSLATORS */
-
     /**
      * Translator object for unescaping escaped Java.
      *
@@ -274,6 +383,7 @@ public class StringEscapeUtils {
      * as the foundation for a custom translator.
      */
     public static final CharSequenceTranslator UNESCAPE_JAVA;
+
     static {
         final Map<CharSequence, CharSequence> unescapeJavaMap = new HashMap<>();
         unescapeJavaMap.put("\\\\", "\\");
@@ -358,6 +468,8 @@ public class StringEscapeUtils {
      */
     public static final CharSequenceTranslator UNESCAPE_CSV = new CsvTranslators.CsvUnescaper();
 
+    /* Helper functions */
+
     /**
      * Translator object for unescaping escaped XSI Value entries.
      *
@@ -368,137 +480,112 @@ public class StringEscapeUtils {
     public static final CharSequenceTranslator UNESCAPE_XSI = new XsiUnescaper();
 
     /**
-     * Translator object for unescaping backslash escaped entries.
+     * Get a {@link Builder}.
+     * @param translator the text translator
+     * @return {@link Builder}
      */
-    static class XsiUnescaper extends CharSequenceTranslator {
-
-        /**
-         * Escaped backslash constant.
-         */
-        private static final char BACKSLASH = '\\';
-
-        @Override
-        public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
-
-            if (index != 0) {
-                throw new IllegalStateException("XsiUnescaper should never reach the [1] index");
-            }
-
-            final String s = input.toString();
-
-            int segmentStart = 0;
-            int searchOffset = 0;
-            while (true) {
-                final int pos = s.indexOf(BACKSLASH, searchOffset);
-                if (pos == -1) {
-                    if (segmentStart < s.length()) {
-                        writer.write(s.substring(segmentStart));
-                    }
-                    break;
-                }
-                if (pos > segmentStart) {
-                    writer.write(s.substring(segmentStart, pos));
-                }
-                segmentStart = pos + 1;
-                searchOffset = pos + 2;
-            }
-
-            return Character.codePointCount(input, 0, input.length());
-        }
+    public static StringEscapeUtils.Builder builder(final CharSequenceTranslator translator) {
+        return new Builder(translator);
     }
 
-    /* Helper functions */
-
     /**
-     * {@code StringEscapeUtils} instances should NOT be constructed in
-     * standard programming.
+     * Returns a {@code String} value for a CSV column enclosed in double quotes,
+     * if required.
      *
-     * <p>Instead, the class should be used as:</p>
-     * <pre>StringEscapeUtils.escapeJava("foo");</pre>
+     * <p>If the value contains a comma, newline or double quote, then the
+     *    String value is returned enclosed in double quotes.</p>
      *
-     * <p>This constructor is public to permit tools that require a JavaBean
-     * instance to operate.</p>
+     * <p>Any double quote characters in the value are escaped with another double quote.</p>
+     *
+     * <p>If the value does not contain a comma, newline or double quote, then the
+     *    String value is returned unchanged.</p>
+     *
+     * see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
+     * <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
+     *
+     * @param input the input CSV column String, may be null
+     * @return The input String, enclosed in double quotes if the value contains a comma,
+     * newline or double quote, {@code null} if null string input
      */
-    public StringEscapeUtils() {
+    public static final String escapeCsv(final String input) {
+        return ESCAPE_CSV.translate(input);
     }
 
     /**
-     * Convenience wrapper for {@link java.lang.StringBuilder} providing escape methods.
+     * Escapes the characters in a {@code String} using EcmaScript String rules.
+     *
+     * <p>Escapes any values it finds into their EcmaScript String form.
+     * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
+     *
+     * <p>So a tab becomes the characters {@code '\\'} and
+     * {@code 't'}.</p>
+     *
+     * <p>The only difference between Java strings and EcmaScript strings
+     * is that in EcmaScript, a single quote and forward-slash (/) are escaped.</p>
+     *
+     * <p>Note that EcmaScript is best known by the JavaScript and ActionScript dialects.</p>
      *
      * <p>Example:</p>
      * <pre>
-     * new Builder(ESCAPE_HTML4)
-     *      .append("&lt;p&gt;")
-     *      .escape("This is paragraph 1 and special chars like &amp; get escaped.")
-     *      .append("&lt;/p&gt;&lt;p&gt;")
-     *      .escape("This is paragraph 2 &amp; more...")
-     *      .append("&lt;/p&gt;")
-     *      .toString()
+     * input string: He didn't say, "Stop!"
+     * output string: He didn\'t say, \"Stop!\"
      * </pre>
      *
+     * <b>Security Note.</b> We only provide backslash escaping in this method. For example, {@code '\"'} has the output
+     * {@code '\\\"'} which could result in potential issues in the case where the string being escaped is being used
+     * in an HTML tag like {@code <select onmouseover="..." />}. If you wish to have more rigorous string escaping, you
+     * may consider the
+     * <a href="https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API_JAVA">ESAPI Libraries</a>.
+     * Further, you can view the <a href="https://github.com/esapi">ESAPI GitHub Org</a>.
+     *
+     * @param input  String to escape values in, may be null
+     * @return String with escaped values, {@code null} if null string input
      */
-    public static final class Builder {
-
-        /**
-         * StringBuilder to be used in the Builder class.
-         */
-        private final StringBuilder sb;
-
-        /**
-         * CharSequenceTranslator to be used in the Builder class.
-         */
-        private final CharSequenceTranslator translator;
+    public static final String escapeEcmaScript(final String input) {
+        return ESCAPE_ECMASCRIPT.translate(input);
+    }
 
-        /**
-         * Builder constructor.
-         *
-         * @param translator a CharSequenceTranslator.
-         */
-        private Builder(final CharSequenceTranslator translator) {
-            this.sb = new StringBuilder();
-            this.translator = translator;
-        }
-
-        /**
-         * Escape {@code input} according to the given {@link CharSequenceTranslator}.
-         *
-         * @param input the String to escape
-         * @return {@code this}, to enable chaining
-         */
-        public Builder escape(final String input) {
-            sb.append(translator.translate(input));
-            return this;
-        }
-
-        /**
-         * Literal append, no escaping being done.
-         *
-         * @param input the String to append
-         * @return {@code this}, to enable chaining
-         */
-        public Builder append(final String input) {
-            sb.append(input);
-            return this;
-        }
-
-        /**
-         * Return the escaped string.
-         *
-         * @return The escaped string
-         */
-        @Override
-        public String toString() {
-            return sb.toString();
-        }
-    }
+    /**
+     * Escapes the characters in a {@code String} using HTML entities.
+     *
+     * <p>Supports only the HTML 3.0 entities.</p>
+     *
+     * @param input  the {@code String} to escape, may be null
+     * @return a new escaped {@code String}, {@code null} if null string input
+     */
+    public static final String escapeHtml3(final String input) {
+        return ESCAPE_HTML3.translate(input);
+    }
 
+    // HTML and XML
+    //--------------------------------------------------------------------------
     /**
-     * Get a {@link Builder}.
-     * @param translator the text translator
-     * @return {@link Builder}
+     * Escapes the characters in a {@code String} using HTML entities.
+     *
+     * <p>
+     * For example:
+     * </p>
+     * <p>{@code "bread" &amp; "butter"}</p>
+     * becomes:
+     * <p>
+     * {@code &amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;}.
+     * </p>
+     *
+     * <p>Supports all known HTML 4.0 entities, including funky accents.
+     * Note that the commonly used apostrophe escape character (&amp;apos;)
+     * is not a legal entity and so is not supported).</p>
+     *
+     * @param input  the {@code String} to escape, may be null
+     * @return a new escaped {@code String}, {@code null} if null string input
+     *
+     * @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
+     * @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
+     * @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
+     * @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
+     * @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
      */
-    public static StringEscapeUtils.Builder builder(final CharSequenceTranslator translator) {
-        return new Builder(translator);
+    public static final String escapeHtml4(final String input) {
+        return ESCAPE_HTML4.translate(input);
     }
 
     // Java and JavaScript
@@ -528,40 +615,6 @@ public class StringEscapeUtils {
     }
 
     /**
-     * Escapes the characters in a {@code String} using EcmaScript String rules.
-     *
-     * <p>Escapes any values it finds into their EcmaScript String form.
-     * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
-     *
-     * <p>So a tab becomes the characters {@code '\\'} and
-     * {@code 't'}.</p>
-     *
-     * <p>The only difference between Java strings and EcmaScript strings
-     * is that in EcmaScript, a single quote and forward-slash (/) are escaped.</p>
-     *
-     * <p>Note that EcmaScript is best known by the JavaScript and ActionScript dialects.</p>
-     *
-     * <p>Example:</p>
-     * <pre>
-     * input string: He didn't say, "Stop!"
-     * output string: He didn\'t say, \"Stop!\"
-     * </pre>
-     *
-     * <b>Security Note.</b> We only provide backslash escaping in this method. For example, {@code '\"'} has the output
-     * {@code '\\\"'} which could result in potential issues in the case where the string being escaped is being used
-     * in an HTML tag like {@code <select onmouseover="..." />}. If you wish to have more rigorous string escaping, you
-     * may consider the
-     * <a href="https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API_JAVA">ESAPI Libraries</a>.
-     * Further, you can view the <a href="https://github.com/esapi">ESAPI GitHub Org</a>.
-     *
-     * @param input  String to escape values in, may be null
-     * @return String with escaped values, {@code null} if null string input
-     */
-    public static final String escapeEcmaScript(final String input) {
-        return ESCAPE_ECMASCRIPT.translate(input);
-    }
-
-    /**
      * Escapes the characters in a {@code String} using Json String rules.
      *
      * <p>Escapes any values it finds into their Json String form.
@@ -589,123 +642,6 @@ public class StringEscapeUtils {
     }
 
     /**
-     * Unescapes any Java literals found in the {@code String}.
-     * For example, it will turn a sequence of {@code '\'} and
-     * {@code 'n'} into a newline character, unless the {@code '\'}
-     * is preceded by another {@code '\'}.
-     *
-     * @param input  the {@code String} to unescape, may be null
-     * @return a new unescaped {@code String}, {@code null} if null string input
-     */
-    public static final String unescapeJava(final String input) {
-        return UNESCAPE_JAVA.translate(input);
-    }
-
-    /**
-     * Unescapes any EcmaScript literals found in the {@code String}.
-     *
-     * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
-     * into a newline character, unless the {@code '\'} is preceded by another
-     * {@code '\'}.</p>
-     *
-     * @see #unescapeJava(String)
-     * @param input  the {@code String} to unescape, may be null
-     * @return A new unescaped {@code String}, {@code null} if null string input
-     */
-    public static final String unescapeEcmaScript(final String input) {
-        return UNESCAPE_ECMASCRIPT.translate(input);
-    }
-
-    /**
-     * Unescapes any Json literals found in the {@code String}.
-     *
-     * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
-     * into a newline character, unless the {@code '\'} is preceded by another
-     * {@code '\'}.</p>
-     *
-     * @see #unescapeJava(String)
-     * @param input  the {@code String} to unescape, may be null
-     * @return A new unescaped {@code String}, {@code null} if null string input
-     */
-    public static final String unescapeJson(final String input) {
-        return UNESCAPE_JSON.translate(input);
-    }
-
-    // HTML and XML
-    //--------------------------------------------------------------------------
-    /**
-     * Escapes the characters in a {@code String} using HTML entities.
-     *
-     * <p>
-     * For example:
-     * </p>
-     * <p>{@code "bread" &amp; "butter"}</p>
-     * becomes:
-     * <p>
-     * {@code &amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;}.
-     * </p>
-     *
-     * <p>Supports all known HTML 4.0 entities, including funky accents.
-     * Note that the commonly used apostrophe escape character (&amp;apos;)
-     * is not a legal entity and so is not supported).</p>
-     *
-     * @param input  the {@code String} to escape, may be null
-     * @return a new escaped {@code String}, {@code null} if null string input
-     *
-     * @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
-     * @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
-     * @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
-     * @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
-     * @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
-     */
-    public static final String escapeHtml4(final String input) {
-        return ESCAPE_HTML4.translate(input);
-    }
-
-    /**
-     * Escapes the characters in a {@code String} using HTML entities.
-     *
-     * <p>Supports only the HTML 3.0 entities.</p>
-     *
-     * @param input  the {@code String} to escape, may be null
-     * @return a new escaped {@code String}, {@code null} if null string input
-     */
-    public static final String escapeHtml3(final String input) {
-        return ESCAPE_HTML3.translate(input);
-    }
-
-    /**
-     * Unescapes a string containing entity escapes to a string
-     * containing the actual Unicode characters corresponding to the
-     * escapes. Supports HTML 4.0 entities.
-     *
-     * <p>For example, the string {@code "&lt;Fran&ccedil;ais&gt;"}
-     * will become {@code "<Fran�ais>"}</p>
-     *
-     * <p>If an entity is unrecognized, it is left alone, and inserted
-     * verbatim into the result string. e.g. {@code "&gt;&zzzz;x"} will
-     * become {@code ">&zzzz;x"}.</p>
-     *
-     * @param input  the {@code String} to unescape, may be null
-     * @return a new unescaped {@code String}, {@code null} if null string input
-     */
-    public static final String unescapeHtml4(final String input) {
-        return UNESCAPE_HTML4.translate(input);
-    }
-
-    /**
-     * Unescapes a string containing entity escapes to a string
-     * containing the actual Unicode characters corresponding to the
-     * escapes. Supports only HTML 3.0 entities.
-     *
-     * @param input  the {@code String} to unescape, may be null
-     * @return a new unescaped {@code String}, {@code null} if null string input
-     */
-    public static final String unescapeHtml3(final String input) {
-        return UNESCAPE_HTML3.translate(input);
-    }
-
-    /**
      * Escapes the characters in a {@code String} using XML entities.
      *
      * <p>For example: {@code "bread" & "butter"} =&gt;
@@ -766,46 +702,24 @@ public class StringEscapeUtils {
     }
 
     /**
-     * Unescapes a string containing XML entity escapes to a string
-     * containing the actual Unicode characters corresponding to the
-     * escapes.
-     *
-     * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
-     * Does not support DTDs or external entities.</p>
-     *
-     * <p>Note that numerical \\u Unicode codes are unescaped to their respective
-     *    Unicode characters. This may change in future releases.</p>
-     *
-     * @param input  the {@code String} to unescape, may be null
-     * @return a new unescaped {@code String}, {@code null} if null string input
-     * @see #escapeXml10(String)
-     * @see #escapeXml11(String)
-     */
-    public static final String unescapeXml(final String input) {
-        return UNESCAPE_XML.translate(input);
-    }
-
-    /**
-     * Returns a {@code String} value for a CSV column enclosed in double quotes,
-     * if required.
-     *
-     * <p>If the value contains a comma, newline or double quote, then the
-     *    String value is returned enclosed in double quotes.</p>
-     *
-     * <p>Any double quote characters in the value are escaped with another double quote.</p>
+     * Escapes the characters in a {@code String} using XSI rules.
      *
-     * <p>If the value does not contain a comma, newline or double quote, then the
-     *    String value is returned unchanged.</p>
+     * <p><b>Beware!</b> In most cases you don't want to escape shell commands but use multi-argument
+     * methods provided by {@link java.lang.ProcessBuilder} or {@link java.lang.Runtime#exec(String[])}
+     * instead.</p>
      *
-     * see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
-     * <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
+     * <p>Example:</p>
+     * <pre>
+     * input string: He didn't say, "Stop!"
+     * output string: He\ didn\'t\ say,\ \"Stop!\"
+     * </pre>
      *
-     * @param input the input CSV column String, may be null
-     * @return The input String, enclosed in double quotes if the value contains a comma,
-     * newline or double quote, {@code null} if null string input
+     * @see <a href="http://pubs.opengroup.org/onlinepubs/7908799/xcu/chap2.html">Shell Command Language</a>
+     * @param input  String to escape values in, may be null
+     * @return String with escaped values, {@code null} if null string input
      */
-    public static final String escapeCsv(final String input) {
-        return ESCAPE_CSV.translate(input);
+    public static final String escapeXSI(final String input) {
+        return ESCAPE_XSI.translate(input);
     }
 
     /**
@@ -833,24 +747,97 @@ public class StringEscapeUtils {
     }
 
     /**
-     * Escapes the characters in a {@code String} using XSI rules.
+     * Unescapes any EcmaScript literals found in the {@code String}.
      *
-     * <p><b>Beware!</b> In most cases you don't want to escape shell commands but use multi-argument
-     * methods provided by {@link java.lang.ProcessBuilder} or {@link java.lang.Runtime#exec(String[])}
-     * instead.</p>
+     * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
+     * into a newline character, unless the {@code '\'} is preceded by another
+     * {@code '\'}.</p>
      *
-     * <p>Example:</p>
-     * <pre>
-     * input string: He didn't say, "Stop!"
-     * output string: He\ didn\'t\ say,\ \"Stop!\"
-     * </pre>
+     * @see #unescapeJava(String)
+     * @param input  the {@code String} to unescape, may be null
+     * @return A new unescaped {@code String}, {@code null} if null string input
+     */
+    public static final String unescapeEcmaScript(final String input) {
+        return UNESCAPE_ECMASCRIPT.translate(input);
+    }
+
+    /**
+     * Unescapes a string containing entity escapes to a string
+     * containing the actual Unicode characters corresponding to the
+     * escapes. Supports only HTML 3.0 entities.
      *
-     * @see <a href="http://pubs.opengroup.org/onlinepubs/7908799/xcu/chap2.html">Shell Command Language</a>
-     * @param input  String to escape values in, may be null
-     * @return String with escaped values, {@code null} if null string input
+     * @param input  the {@code String} to unescape, may be null
+     * @return a new unescaped {@code String}, {@code null} if null string input
      */
-    public static final String escapeXSI(final String input) {
-        return ESCAPE_XSI.translate(input);
+    public static final String unescapeHtml3(final String input) {
+        return UNESCAPE_HTML3.translate(input);
+    }
+
+    /**
+     * Unescapes a string containing entity escapes to a string
+     * containing the actual Unicode characters corresponding to the
+     * escapes. Supports HTML 4.0 entities.
+     *
+     * <p>For example, the string {@code "&lt;Fran&ccedil;ais&gt;"}
+     * will become {@code "<Fran�ais>"}</p>
+     *
+     * <p>If an entity is unrecognized, it is left alone, and inserted
+     * verbatim into the result string. e.g. {@code "&gt;&zzzz;x"} will
+     * become {@code ">&zzzz;x"}.</p>
+     *
+     * @param input  the {@code String} to unescape, may be null
+     * @return a new unescaped {@code String}, {@code null} if null string input
+     */
+    public static final String unescapeHtml4(final String input) {
+        return UNESCAPE_HTML4.translate(input);
+    }
+
+    /**
+     * Unescapes any Java literals found in the {@code String}.
+     * For example, it will turn a sequence of {@code '\'} and
+     * {@code 'n'} into a newline character, unless the {@code '\'}
+     * is preceded by another {@code '\'}.
+     *
+     * @param input  the {@code String} to unescape, may be null
+     * @return a new unescaped {@code String}, {@code null} if null string input
+     */
+    public static final String unescapeJava(final String input) {
+        return UNESCAPE_JAVA.translate(input);
+    }
+
+    /**
+     * Unescapes any Json literals found in the {@code String}.
+     *
+     * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
+     * into a newline character, unless the {@code '\'} is preceded by another
+     * {@code '\'}.</p>
+     *
+     * @see #unescapeJava(String)
+     * @param input  the {@code String} to unescape, may be null
+     * @return A new unescaped {@code String}, {@code null} if null string input
+     */
+    public static final String unescapeJson(final String input) {
+        return UNESCAPE_JSON.translate(input);
+    }
+
+    /**
+     * Unescapes a string containing XML entity escapes to a string
+     * containing the actual Unicode characters corresponding to the
+     * escapes.
+     *
+     * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
+     * Does not support DTDs or external entities.</p>
+     *
+     * <p>Note that numerical \\u Unicode codes are unescaped to their respective
+     *    Unicode characters. This may change in future releases.</p>
+     *
+     * @param input  the {@code String} to unescape, may be null
+     * @return a new unescaped {@code String}, {@code null} if null string input
+     * @see #escapeXml10(String)
+     * @see #escapeXml11(String)
+     */
+    public static final String unescapeXml(final String input) {
+        return UNESCAPE_XML.translate(input);
     }
 
     /**
@@ -864,4 +851,17 @@ public class StringEscapeUtils {
         return UNESCAPE_XSI.translate(input);
     }
 
+    /**
+     * {@code StringEscapeUtils} instances should NOT be constructed in
+     * standard programming.
+     *
+     * <p>Instead, the class should be used as:</p>
+     * <pre>StringEscapeUtils.escapeJava("foo");</pre>
+     *
+     * <p>This constructor is public to permit tools that require a JavaBean
+     * instance to operate.</p>
+     */
+    public StringEscapeUtils() {
+    }
+
 }
diff --git a/src/main/java/org/apache/commons/text/WordUtils.java b/src/main/java/org/apache/commons/text/WordUtils.java
index 6511e4c..e0e70ba 100644
--- a/src/main/java/org/apache/commons/text/WordUtils.java
+++ b/src/main/java/org/apache/commons/text/WordUtils.java
@@ -38,408 +38,146 @@ import org.apache.commons.lang3.Validate;
 public class WordUtils {
 
     /**
-     * {@code WordUtils} instances should NOT be constructed in
-     * standard programming. Instead, the class should be used as
-     * {@code WordUtils.wrap("foo bar", 20);}.
+     * Abbreviates the words nicely.
      *
-     * <p>This constructor is public to permit tools that require a JavaBean
-     * instance to operate.</p>
+     * <p>
+     * This method searches for the first space after the lower limit and abbreviates
+     * the String there. It will also append any String passed as a parameter
+     * to the end of the String. The upper limit can be specified to forcibly
+     * abbreviate a String.
+     * </p>
+     *
+     * @param str         the string to be abbreviated. If null is passed, null is returned.
+     *                    If the empty String is passed, the empty string is returned.
+     * @param lower       the lower limit; negative value is treated as zero.
+     * @param upper       the upper limit; specify -1 if no limit is desired.
+     *                    If the upper limit is lower than the lower limit, it will be
+     *                    adjusted to be the same as the lower limit.
+     * @param appendToEnd String to be appended to the end of the abbreviated string.
+     *                    This is appended ONLY if the string was indeed abbreviated.
+     *                    The append does not count towards the lower or upper limits.
+     * @return The abbreviated String.
+     *
+     * <pre>
+     * WordUtils.abbreviate("Now is the time for all good men", 0, 40, null));     = "Now"
+     * WordUtils.abbreviate("Now is the time for all good men", 10, 40, null));    = "Now is the"
+     * WordUtils.abbreviate("Now is the time for all good men", 20, 40, null));    = "Now is the time for all"
+     * WordUtils.abbreviate("Now is the time for all good men", 0, 40, ""));       = "Now"
+     * WordUtils.abbreviate("Now is the time for all good men", 10, 40, ""));      = "Now is the"
+     * WordUtils.abbreviate("Now is the time for all good men", 20, 40, ""));      = "Now is the time for all"
+     * WordUtils.abbreviate("Now is the time for all good men", 0, 40, " ..."));   = "Now ..."
+     * WordUtils.abbreviate("Now is the time for all good men", 10, 40, " ..."));  = "Now is the ..."
+     * WordUtils.abbreviate("Now is the time for all good men", 20, 40, " ..."));  = "Now is the time for all ..."
+     * WordUtils.abbreviate("Now is the time for all good men", 0, -1, ""));       = "Now"
+     * WordUtils.abbreviate("Now is the time for all good men", 10, -1, ""));      = "Now is the"
+     * WordUtils.abbreviate("Now is the time for all good men", 20, -1, ""));      = "Now is the time for all"
+     * WordUtils.abbreviate("Now is the time for all good men", 50, -1, ""));      = "Now is the time for all good men"
+     * WordUtils.abbreviate("Now is the time for all good men", 1000, -1, ""));    = "Now is the time for all good men"
+     * WordUtils.abbreviate("Now is the time for all good men", 9, -10, null));    = IllegalArgumentException
+     * WordUtils.abbreviate("Now is the time for all good men", 10, 5, null));     = IllegalArgumentException
+     * </pre>
      */
-    public WordUtils() {
+    public static String abbreviate(final String str, int lower, int upper, final String appendToEnd) {
+        Validate.isTrue(upper >= -1, "upper value cannot be less than -1");
+        Validate.isTrue(upper >= lower || upper == -1, "upper value is less than lower value");
+        if (StringUtils.isEmpty(str)) {
+            return str;
+        }
+
+        // if the lower value is greater than the length of the string,
+        // set to the length of the string
+        if (lower > str.length()) {
+            lower = str.length();
+        }
+
+        // if the upper value is -1 (i.e. no limit) or is greater
+        // than the length of the string, set to the length of the string
+        if (upper == -1 || upper > str.length()) {
+            upper = str.length();
+        }
+
+        final StringBuilder result = new StringBuilder();
+        final int index = StringUtils.indexOf(str, " ", lower);
+        if (index == -1) {
+            result.append(str, 0, upper);
+            // only if abbreviation has occurred do we append the appendToEnd value
+            if (upper != str.length()) {
+                result.append(StringUtils.defaultString(appendToEnd));
+            }
+        } else if (index > upper) {
+            result.append(str, 0, upper);
+            result.append(StringUtils.defaultString(appendToEnd));
+        } else {
+            result.append(str, 0, index);
+            result.append(StringUtils.defaultString(appendToEnd));
+        }
+
+        return result.toString();
     }
 
     /**
-     * Wraps a single line of text, identifying words by {@code ' '}.
-     *
-     * <p>New lines will be separated by the system property line separator.
-     * Very long words, such as URLs will <i>not</i> be wrapped.</p>
-     *
-     * <p>Leading spaces on a new line are stripped.
-     * Trailing spaces are not stripped.</p>
+     * Capitalizes all the whitespace separated words in a String.
+     * Only the first character of each word is changed. To convert the
+     * rest of each word to lowercase at the same time,
+     * use {@link #capitalizeFully(String)}.
      *
-     * <table border="1">
-     *  <caption>Examples</caption>
-     *  <tr>
-     *   <th>input</th>
-     *   <th>wrapLength</th>
-     *   <th>result</th>
-     *  </tr>
-     *  <tr>
-     *   <td>null</td>
-     *   <td>*</td>
-     *   <td>null</td>
-     *  </tr>
-     *  <tr>
-     *   <td>""</td>
-     *   <td>*</td>
-     *   <td>""</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
-     *   <td>20</td>
-     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Click here, https://commons.apache.org, to jump to the commons website"</td>
-     *   <td>20</td>
-     *   <td>"Click here,\nhttps://commons.apache.org,\nto jump to the\ncommons website"</td>
-     *  </tr>
-     * </table>
+     * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
+     * A {@code null} input String returns {@code null}.
+     * Capitalization uses the Unicode title case, normally equivalent to
+     * upper case.</p>
      *
-     * (assuming that '\n' is the systems line separator)
+     * <pre>
+     * WordUtils.capitalize(null)        = null
+     * WordUtils.capitalize("")          = ""
+     * WordUtils.capitalize("i am FINE") = "I Am FINE"
+     * </pre>
      *
-     * @param str  the String to be word wrapped, may be null
-     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
-     * @return a line with newlines inserted, {@code null} if null input
+     * @param str  the String to capitalize, may be null
+     * @return capitalized String, {@code null} if null String input
+     * @see #uncapitalize(String)
+     * @see #capitalizeFully(String)
      */
-    public static String wrap(final String str, final int wrapLength) {
-        return wrap(str, wrapLength, null, false);
+    public static String capitalize(final String str) {
+        return capitalize(str, null);
     }
 
     /**
-     * Wraps a single line of text, identifying words by {@code ' '}.
+     * Capitalizes all the delimiter separated words in a String.
+     * Only the first character of each word is changed. To convert the
+     * rest of each word to lowercase at the same time,
+     * use {@link #capitalizeFully(String, char[])}.
      *
-     * <p>Leading spaces on a new line are stripped.
-     * Trailing spaces are not stripped.</p>
+     * <p>The delimiters represent a set of characters understood to separate words.
+     * The first string character and the first non-delimiter character after a
+     * delimiter will be capitalized.</p>
      *
-     * <table border="1">
-     *  <caption>Examples</caption>
-     *  <tr>
-     *   <th>input</th>
-     *   <th>wrapLength</th>
-     *   <th>newLineString</th>
-     *   <th>wrapLongWords</th>
-     *   <th>result</th>
-     *  </tr>
-     *  <tr>
-     *   <td>null</td>
-     *   <td>*</td>
-     *   <td>*</td>
-     *   <td>true/false</td>
-     *   <td>null</td>
-     *  </tr>
-     *  <tr>
-     *   <td>""</td>
-     *   <td>*</td>
-     *   <td>*</td>
-     *   <td>true/false</td>
-     *   <td>""</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>true/false</td>
-     *   <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>"&lt;br /&gt;"</td>
-     *   <td>true/false</td>
-     *   <td>"Here is one line of&lt;br /&gt;text that is going&lt;
-     *   br /&gt;to be wrapped after&lt;br /&gt;20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>null</td>
-     *   <td>true/false</td>
-     *   <td>"Here is one line of" + systemNewLine + "text that is going"
-     *   + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>false</td>
-     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>true</td>
-     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"</td>
-     *  </tr>
-     * </table>
+     * <p>A {@code null} input String returns {@code null}.
+     * Capitalization uses the Unicode title case, normally equivalent to
+     * upper case.</p>
      *
-     * @param str  the String to be word wrapped, may be null
-     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
-     * @param newLineStr  the string to insert for a new line,
-     *  {@code null} uses the system property line separator
-     * @param wrapLongWords  true if long words (such as URLs) should be wrapped
-     * @return a line with newlines inserted, {@code null} if null input
+     * <pre>
+     * WordUtils.capitalize(null, *)            = null
+     * WordUtils.capitalize("", *)              = ""
+     * WordUtils.capitalize(*, new char[0])     = *
+     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
+     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
+     * WordUtils.capitalize("i am fine", new char[]{}) = "I am fine"
+     * </pre>
+     *
+     * @param str  the String to capitalize, may be null
+     * @param delimiters  set of characters to determine capitalization, null means whitespace
+     * @return capitalized String, {@code null} if null String input
+     * @see #uncapitalize(String)
+     * @see #capitalizeFully(String)
      */
-    public static String wrap(final String str,
-                              final int wrapLength,
-                              final String newLineStr,
-                              final boolean wrapLongWords) {
-        return wrap(str, wrapLength, newLineStr, wrapLongWords, " ");
-    }
-
-    /**
-     * Wraps a single line of text, identifying words by {@code wrapOn}.
-     *
-     * <p>Leading spaces on a new line are stripped.
-     * Trailing spaces are not stripped.</p>
-     *
-     * <table border="1">
-     *  <caption>Examples</caption>
-     *  <tr>
-     *   <th>input</th>
-     *   <th>wrapLength</th>
-     *   <th>newLineString</th>
-     *   <th>wrapLongWords</th>
-     *   <th>wrapOn</th>
-     *   <th>result</th>
-     *  </tr>
-     *  <tr>
-     *   <td>null</td>
-     *   <td>*</td>
-     *   <td>*</td>
-     *   <td>true/false</td>
-     *   <td>*</td>
-     *   <td>null</td>
-     *  </tr>
-     *  <tr>
-     *   <td>""</td>
-     *   <td>*</td>
-     *   <td>*</td>
-     *   <td>true/false</td>
-     *   <td>*</td>
-     *   <td>""</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>true/false</td>
-     *   <td>" "</td>
-     *   <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>"&lt;br /&gt;"</td>
-     *   <td>true/false</td>
-     *   <td>" "</td>
-     *   <td>"Here is one line of&lt;br /&gt;text that is going&lt;br /&gt;
-     *   to be wrapped after&lt;br /&gt;20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
-     *   <td>20</td>
-     *   <td>null</td>
-     *   <td>true/false</td>
-     *   <td>" "</td>
-     *   <td>"Here is one line of" + systemNewLine + "text that is going"
-     *   + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>false</td>
-     *   <td>" "</td>
-     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>true</td>
-     *   <td>" "</td>
-     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"</td>
-     *  </tr>
-     *  <tr>
-     *   <td>"flammable/inflammable"</td>
-     *   <td>20</td>
-     *   <td>"\n"</td>
-     *   <td>true</td>
-     *   <td>"/"</td>
-     *   <td>"flammable\ninflammable"</td>
-     *  </tr>
-     * </table>
-     * @param str  the String to be word wrapped, may be null
-     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
-     * @param newLineStr  the string to insert for a new line,
-     *  {@code null} uses the system property line separator
-     * @param wrapLongWords  true if long words (such as URLs) should be wrapped
-     * @param wrapOn regex expression to be used as a breakable characters,
-     *               if blank string is provided a space character will be used
-     * @return a line with newlines inserted, {@code null} if null input
-     */
-    public static String wrap(final String str,
-                              int wrapLength,
-                              String newLineStr,
-                              final boolean wrapLongWords,
-                              String wrapOn) {
-        if (str == null) {
-            return null;
-        }
-        if (newLineStr == null) {
-            newLineStr = System.lineSeparator();
-        }
-        if (wrapLength < 1) {
-            wrapLength = 1;
-        }
-        if (StringUtils.isBlank(wrapOn)) {
-            wrapOn = " ";
-        }
-        final Pattern patternToWrapOn = Pattern.compile(wrapOn);
-        final int inputLineLength = str.length();
-        int offset = 0;
-        final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);
-        int matcherSize = -1;
-
-        while (offset < inputLineLength) {
-            int spaceToWrapAt = -1;
-            Matcher matcher = patternToWrapOn.matcher(str.substring(offset,
-                    Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength)));
-            if (matcher.find()) {
-                if (matcher.start() == 0) {
-                    matcherSize = matcher.end();
-                    if (matcherSize != 0) {
-                        offset += matcher.end();
-                        continue;
-                    }
-                    offset += 1;
-                }
-                spaceToWrapAt = matcher.start() + offset;
-            }
-
-            // only last line without leading spaces is left
-            if (inputLineLength - offset <= wrapLength) {
-                break;
-            }
-
-            while (matcher.find()) {
-                spaceToWrapAt = matcher.start() + offset;
-            }
-
-            if (spaceToWrapAt >= offset) {
-                // normal case
-                wrappedLine.append(str, offset, spaceToWrapAt);
-                wrappedLine.append(newLineStr);
-                offset = spaceToWrapAt + 1;
-
-            } else {
-                // really long word or URL
-                if (wrapLongWords) {
-                    if (matcherSize == 0) {
-                        offset--;
-                    }
-                    // wrap really long word one line at a time
-                    wrappedLine.append(str, offset, wrapLength + offset);
-                    wrappedLine.append(newLineStr);
-                    offset += wrapLength;
-                    matcherSize = -1;
-                } else {
-                    // do not wrap really long word, just extend beyond limit
-                    matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength));
-                    if (matcher.find()) {
-                        matcherSize = matcher.end() - matcher.start();
-                        spaceToWrapAt = matcher.start() + offset + wrapLength;
-                    }
-
-                    if (spaceToWrapAt >= 0) {
-                        if (matcherSize == 0 && offset != 0) {
-                            offset--;
-                        }
-                        wrappedLine.append(str, offset, spaceToWrapAt);
-                        wrappedLine.append(newLineStr);
-                        offset = spaceToWrapAt + 1;
-                    } else {
-                        if (matcherSize == 0 && offset != 0) {
-                            offset--;
-                        }
-                        wrappedLine.append(str, offset, str.length());
-                        offset = inputLineLength;
-                        matcherSize = -1;
-                    }
-                }
-            }
-        }
-
-        if (matcherSize == 0 && offset < inputLineLength) {
-            offset--;
-        }
-
-        // Whatever is left in line is short enough to just pass through
-        wrappedLine.append(str, offset, str.length());
-
-        return wrappedLine.toString();
-    }
-
-    /**
-     * Capitalizes all the whitespace separated words in a String.
-     * Only the first character of each word is changed. To convert the
-     * rest of each word to lowercase at the same time,
-     * use {@link #capitalizeFully(String)}.
-     *
-     * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
-     * A {@code null} input String returns {@code null}.
-     * Capitalization uses the Unicode title case, normally equivalent to
-     * upper case.</p>
-     *
-     * <pre>
-     * WordUtils.capitalize(null)        = null
-     * WordUtils.capitalize("")          = ""
-     * WordUtils.capitalize("i am FINE") = "I Am FINE"
-     * </pre>
-     *
-     * @param str  the String to capitalize, may be null
-     * @return capitalized String, {@code null} if null String input
-     * @see #uncapitalize(String)
-     * @see #capitalizeFully(String)
-     */
-    public static String capitalize(final String str) {
-        return capitalize(str, null);
-    }
-
-    /**
-     * Capitalizes all the delimiter separated words in a String.
-     * Only the first character of each word is changed. To convert the
-     * rest of each word to lowercase at the same time,
-     * use {@link #capitalizeFully(String, char[])}.
-     *
-     * <p>The delimiters represent a set of characters understood to separate words.
-     * The first string character and the first non-delimiter character after a
-     * delimiter will be capitalized.</p>
-     *
-     * <p>A {@code null} input String returns {@code null}.
-     * Capitalization uses the Unicode title case, normally equivalent to
-     * upper case.</p>
-     *
-     * <pre>
-     * WordUtils.capitalize(null, *)            = null
-     * WordUtils.capitalize("", *)              = ""
-     * WordUtils.capitalize(*, new char[0])     = *
-     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
-     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
-     * WordUtils.capitalize("i am fine", new char[]{}) = "I am fine"
-     * </pre>
-     *
-     * @param str  the String to capitalize, may be null
-     * @param delimiters  set of characters to determine capitalization, null means whitespace
-     * @return capitalized String, {@code null} if null String input
-     * @see #uncapitalize(String)
-     * @see #capitalizeFully(String)
-     */
-    public static String capitalize(final String str, final char... delimiters) {
-        if (StringUtils.isEmpty(str)) {
-            return str;
-        }
-        final Set<Integer> delimiterSet = generateDelimiterSet(delimiters);
-        final int strLen = str.length();
-        final int[] newCodePoints = new int[strLen];
-        int outOffset = 0;
+    public static String capitalize(final String str, final char... delimiters) {
+        if (StringUtils.isEmpty(str)) {
+            return str;
+        }
+        final Set<Integer> delimiterSet = generateDelimiterSet(delimiters);
+        final int strLen = str.length();
+        final int[] newCodePoints = new int[strLen];
+        int outOffset = 0;
 
         boolean capitalizeNext = true;
         for (int index = 0; index < strLen;) {
@@ -519,79 +257,182 @@ public class WordUtils {
     }
 
     /**
-     * Uncapitalizes all the whitespace separated words in a String.
-     * Only the first character of each word is changed.
+     * Checks if the String contains all words in the given array.
      *
-     * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
-     * A {@code null} input String returns {@code null}.</p>
+     * <p>
+     * A {@code null} String will return {@code false}. A {@code null}, zero
+     * length search array or if one element of array is null will return {@code false}.
+     * </p>
      *
      * <pre>
-     * WordUtils.uncapitalize(null)        = null
-     * WordUtils.uncapitalize("")          = ""
-     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
+     * WordUtils.containsAllWords(null, *)            = false
+     * WordUtils.containsAllWords("", *)              = false
+     * WordUtils.containsAllWords(*, null)            = false
+     * WordUtils.containsAllWords(*, [])              = false
+     * WordUtils.containsAllWords("abcd", "ab", "cd") = false
+     * WordUtils.containsAllWords("abc def", "def", "abc") = true
      * </pre>
      *
-     * @param str  the String to uncapitalize, may be null
-     * @return uncapitalized String, {@code null} if null String input
-     * @see #capitalize(String)
+     * @param word The CharSequence to check, may be null
+     * @param words The array of String words to search for, may be null
+     * @return {@code true} if all search words are found, {@code false} otherwise
      */
-    public static String uncapitalize(final String str) {
-        return uncapitalize(str, null);
+    public static boolean containsAllWords(final CharSequence word, final CharSequence... words) {
+        if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) {
+            return false;
+        }
+        for (final CharSequence w : words) {
+            if (StringUtils.isBlank(w)) {
+                return false;
+            }
+            final Pattern p = Pattern.compile(".*\\b" + w + "\\b.*");
+            if (!p.matcher(word).matches()) {
+                return false;
+            }
+        }
+        return true;
     }
 
     /**
-     * Uncapitalizes all the whitespace separated words in a String.
-     * Only the first character of each word is changed.
+     * Converts an array of delimiters to a hash set of code points. Code point of space(32) is added as the default
+     * value if delimiters is null. The generated hash set provides O(1) lookup time.
      *
-     * <p>The delimiters represent a set of characters understood to separate words.
-     * The first string character and the first non-delimiter character after a
-     * delimiter will be uncapitalized.</p>
+     * @param delimiters set of characters to determine capitalization, null means whitespace
+     * @return Set<Integer>
+     */
+    private static Set<Integer> generateDelimiterSet(final char[] delimiters) {
+        final Set<Integer> delimiterHashSet = new HashSet<>();
+        if (delimiters == null || delimiters.length == 0) {
+            if (delimiters == null) {
+                delimiterHashSet.add(Character.codePointAt(new char[] {' '}, 0));
+            }
+
+            return delimiterHashSet;
+        }
+
+        for (int index = 0; index < delimiters.length; index++) {
+            delimiterHashSet.add(Character.codePointAt(delimiters, index));
+        }
+        return delimiterHashSet;
+    }
+
+    /**
+     * Extracts the initial characters from each word in the String.
+     *
+     * <p>All first characters after whitespace are returned as a new string.
+     * Their case is not changed.</p>
      *
      * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
      * A {@code null} input String returns {@code null}.</p>
      *
      * <pre>
-     * WordUtils.uncapitalize(null, *)            = null
-     * WordUtils.uncapitalize("", *)              = ""
-     * WordUtils.uncapitalize(*, null)            = *
-     * WordUtils.uncapitalize(*, new char[0])     = *
-     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
-     * WordUtils.uncapitalize("I am fine", new char[]{}) = "i am fine"
+     * WordUtils.initials(null)             = null
+     * WordUtils.initials("")               = ""
+     * WordUtils.initials("Ben John Lee")   = "BJL"
+     * WordUtils.initials("Ben J.Lee")      = "BJ"
      * </pre>
      *
-     * @param str  the String to uncapitalize, may be null
-     * @param delimiters  set of characters to determine uncapitalization, null means whitespace
-     * @return uncapitalized String, {@code null} if null String input
-     * @see #capitalize(String)
+     * @param str  the String to get initials from, may be null
+     * @return String of initial letters, {@code null} if null String input
+     * @see #initials(String,char[])
      */
-    public static String uncapitalize(final String str, final char... delimiters) {
+    public static String initials(final String str) {
+        return initials(str, null);
+    }
+
+    /**
+     * Extracts the initial characters from each word in the String.
+     *
+     * <p>All first characters after the defined delimiters are returned as a new string.
+     * Their case is not changed.</p>
+     *
+     * <p>If the delimiters array is null, then Whitespace is used.
+     * Whitespace is defined by {@link Character#isWhitespace(char)}.
+     * A {@code null} input String returns {@code null}.
+     * An empty delimiter array returns an empty String.</p>
+     *
+     * <pre>
+     * WordUtils.initials(null, *)                = null
+     * WordUtils.initials("", *)                  = ""
+     * WordUtils.initials("Ben John Lee", null)   = "BJL"
+     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
+     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
+     * WordUtils.initials(*, new char[0])         = ""
+     * </pre>
+     *
+     * @param str  the String to get initials from, may be null
+     * @param delimiters  set of characters to determine words, null means whitespace
+     * @return String of initial characters, {@code null} if null String input
+     * @see #initials(String)
+     */
+    public static String initials(final String str, final char... delimiters) {
         if (StringUtils.isEmpty(str)) {
             return str;
         }
+        if (delimiters != null && delimiters.length == 0) {
+            return StringUtils.EMPTY;
+        }
         final Set<Integer> delimiterSet = generateDelimiterSet(delimiters);
         final int strLen = str.length();
-        final int[] newCodePoints = new int[strLen];
-        int outOffset = 0;
+        final int[] newCodePoints = new int[strLen / 2 + 1];
+        int count = 0;
+        boolean lastWasGap = true;
+        for (int i = 0; i < strLen;) {
+            final int codePoint = str.codePointAt(i);
 
-        boolean uncapitalizeNext = true;
-        for (int index = 0; index < strLen;) {
-            final int codePoint = str.codePointAt(index);
+            if (delimiterSet.contains(codePoint) || (delimiters == null && Character.isWhitespace(codePoint))) {
+                lastWasGap = true;
+            } else if (lastWasGap) {
+                newCodePoints[count++] = codePoint;
+                lastWasGap = false;
+            }
 
-            if (delimiterSet.contains(codePoint)) {
-                uncapitalizeNext = true;
-                newCodePoints[outOffset++] = codePoint;
-                index += Character.charCount(codePoint);
-            } else if (uncapitalizeNext) {
-                final int titleCaseCodePoint = Character.toLowerCase(codePoint);
-                newCodePoints[outOffset++] = titleCaseCodePoint;
-                index += Character.charCount(titleCaseCodePoint);
-                uncapitalizeNext = false;
-            } else {
-                newCodePoints[outOffset++] = codePoint;
-                index += Character.charCount(codePoint);
+            i += Character.charCount(codePoint);
+        }
+        return new String(newCodePoints, 0, count);
+    }
+
+    /**
+     * Is the character a delimiter.
+     *
+     * @param ch the character to check
+     * @param delimiters the delimiters
+     * @return true if it is a delimiter
+     * @deprecated as of 1.2 and will be removed in 2.0
+     */
+    @Deprecated
+    public static boolean isDelimiter(final char ch, final char[] delimiters) {
+        if (delimiters == null) {
+            return Character.isWhitespace(ch);
+        }
+        for (final char delimiter : delimiters) {
+            if (ch == delimiter) {
+                return true;
             }
         }
-        return new String(newCodePoints, 0, outOffset);
+        return false;
+    }
+
+    /**
+     * Is the codePoint a delimiter.
+     *
+     * @param codePoint the codePint to check
+     * @param delimiters the delimiters
+     * @return true if it is a delimiter
+     * @deprecated as of 1.2 and will be removed in 2.0
+     */
+    @Deprecated
+    public static boolean isDelimiter(final int codePoint, final char[] delimiters) {
+        if (delimiters == null) {
+            return Character.isWhitespace(codePoint);
+        }
+        for (int index = 0; index < delimiters.length; index++) {
+            final int delimiterCodePoint = Character.codePointAt(delimiters, index);
+            if (delimiterCodePoint == codePoint) {
+                return true;
+            }
+        }
+        return false;
     }
 
     /**
@@ -648,259 +489,418 @@ public class WordUtils {
     }
 
     /**
-     * Extracts the initial characters from each word in the String.
-     *
-     * <p>All first characters after whitespace are returned as a new string.
-     * Their case is not changed.</p>
+     * Uncapitalizes all the whitespace separated words in a String.
+     * Only the first character of each word is changed.
      *
      * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
      * A {@code null} input String returns {@code null}.</p>
      *
      * <pre>
-     * WordUtils.initials(null)             = null
-     * WordUtils.initials("")               = ""
-     * WordUtils.initials("Ben John Lee")   = "BJL"
-     * WordUtils.initials("Ben J.Lee")      = "BJ"
+     * WordUtils.uncapitalize(null)        = null
+     * WordUtils.uncapitalize("")          = ""
+     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
      * </pre>
      *
-     * @param str  the String to get initials from, may be null
-     * @return String of initial letters, {@code null} if null String input
-     * @see #initials(String,char[])
+     * @param str  the String to uncapitalize, may be null
+     * @return uncapitalized String, {@code null} if null String input
+     * @see #capitalize(String)
      */
-    public static String initials(final String str) {
-        return initials(str, null);
+    public static String uncapitalize(final String str) {
+        return uncapitalize(str, null);
     }
 
     /**
-     * Extracts the initial characters from each word in the String.
+     * Uncapitalizes all the whitespace separated words in a String.
+     * Only the first character of each word is changed.
      *
-     * <p>All first characters after the defined delimiters are returned as a new string.
-     * Their case is not changed.</p>
+     * <p>The delimiters represent a set of characters understood to separate words.
+     * The first string character and the first non-delimiter character after a
+     * delimiter will be uncapitalized.</p>
      *
-     * <p>If the delimiters array is null, then Whitespace is used.
-     * Whitespace is defined by {@link Character#isWhitespace(char)}.
-     * A {@code null} input String returns {@code null}.
-     * An empty delimiter array returns an empty String.</p>
+     * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
+     * A {@code null} input String returns {@code null}.</p>
      *
      * <pre>
-     * WordUtils.initials(null, *)                = null
-     * WordUtils.initials("", *)                  = ""
-     * WordUtils.initials("Ben John Lee", null)   = "BJL"
-     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
-     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
-     * WordUtils.initials(*, new char[0])         = ""
+     * WordUtils.uncapitalize(null, *)            = null
+     * WordUtils.uncapitalize("", *)              = ""
+     * WordUtils.uncapitalize(*, null)            = *
+     * WordUtils.uncapitalize(*, new char[0])     = *
+     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
+     * WordUtils.uncapitalize("I am fine", new char[]{}) = "i am fine"
      * </pre>
      *
-     * @param str  the String to get initials from, may be null
-     * @param delimiters  set of characters to determine words, null means whitespace
-     * @return String of initial characters, {@code null} if null String input
-     * @see #initials(String)
+     * @param str  the String to uncapitalize, may be null
+     * @param delimiters  set of characters to determine uncapitalization, null means whitespace
+     * @return uncapitalized String, {@code null} if null String input
+     * @see #capitalize(String)
      */
-    public static String initials(final String str, final char... delimiters) {
+    public static String uncapitalize(final String str, final char... delimiters) {
         if (StringUtils.isEmpty(str)) {
             return str;
         }
-        if (delimiters != null && delimiters.length == 0) {
-            return StringUtils.EMPTY;
+        final Set<Integer> delimiterSet = generateDelimiterSet(delimiters);
+        final int strLen = str.length();
+        final int[] newCodePoints = new int[strLen];
+        int outOffset = 0;
+
+        boolean uncapitalizeNext = true;
+        for (int index = 0; index < strLen;) {
+            final int codePoint = str.codePointAt(index);
+
+            if (delimiterSet.contains(codePoint)) {
+                uncapitalizeNext = true;
+                newCodePoints[outOffset++] = codePoint;
+                index += Character.charCount(codePoint);
+            } else if (uncapitalizeNext) {
+                final int titleCaseCodePoint = Character.toLowerCase(codePoint);
+                newCodePoints[outOffset++] = titleCaseCodePoint;
+                index += Character.charCount(titleCaseCodePoint);
+                uncapitalizeNext = false;
+            } else {
+                newCodePoints[outOffset++] = codePoint;
+                index += Character.charCount(codePoint);
+            }
+        }
+        return new String(newCodePoints, 0, outOffset);
+    }
+
+    /**
+     * Wraps a single line of text, identifying words by {@code ' '}.
+     *
+     * <p>New lines will be separated by the system property line separator.
+     * Very long words, such as URLs will <i>not</i> be wrapped.</p>
+     *
+     * <p>Leading spaces on a new line are stripped.
+     * Trailing spaces are not stripped.</p>
+     *
+     * <table border="1">
+     *  <caption>Examples</caption>
+     *  <tr>
+     *   <th>input</th>
+     *   <th>wrapLength</th>
+     *   <th>result</th>
+     *  </tr>
+     *  <tr>
+     *   <td>null</td>
+     *   <td>*</td>
+     *   <td>null</td>
+     *  </tr>
+     *  <tr>
+     *   <td>""</td>
+     *   <td>*</td>
+     *   <td>""</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
+     *   <td>20</td>
+     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Click here, https://commons.apache.org, to jump to the commons website"</td>
+     *   <td>20</td>
+     *   <td>"Click here,\nhttps://commons.apache.org,\nto jump to the\ncommons website"</td>
+     *  </tr>
+     * </table>
+     *
+     * (assuming that '\n' is the systems line separator)
+     *
+     * @param str  the String to be word wrapped, may be null
+     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
+     * @return a line with newlines inserted, {@code null} if null input
+     */
+    public static String wrap(final String str, final int wrapLength) {
+        return wrap(str, wrapLength, null, false);
+    }
+
+    /**
+     * Wraps a single line of text, identifying words by {@code ' '}.
+     *
+     * <p>Leading spaces on a new line are stripped.
+     * Trailing spaces are not stripped.</p>
+     *
+     * <table border="1">
+     *  <caption>Examples</caption>
+     *  <tr>
+     *   <th>input</th>
+     *   <th>wrapLength</th>
+     *   <th>newLineString</th>
+     *   <th>wrapLongWords</th>
+     *   <th>result</th>
+     *  </tr>
+     *  <tr>
+     *   <td>null</td>
+     *   <td>*</td>
+     *   <td>*</td>
+     *   <td>true/false</td>
+     *   <td>null</td>
+     *  </tr>
+     *  <tr>
+     *   <td>""</td>
+     *   <td>*</td>
+     *   <td>*</td>
+     *   <td>true/false</td>
+     *   <td>""</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>true/false</td>
+     *   <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>"&lt;br /&gt;"</td>
+     *   <td>true/false</td>
+     *   <td>"Here is one line of&lt;br /&gt;text that is going&lt;
+     *   br /&gt;to be wrapped after&lt;br /&gt;20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>null</td>
+     *   <td>true/false</td>
+     *   <td>"Here is one line of" + systemNewLine + "text that is going"
+     *   + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>false</td>
+     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>true</td>
+     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"</td>
+     *  </tr>
+     * </table>
+     *
+     * @param str  the String to be word wrapped, may be null
+     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
+     * @param newLineStr  the string to insert for a new line,
+     *  {@code null} uses the system property line separator
+     * @param wrapLongWords  true if long words (such as URLs) should be wrapped
+     * @return a line with newlines inserted, {@code null} if null input
+     */
+    public static String wrap(final String str,
+                              final int wrapLength,
+                              final String newLineStr,
+                              final boolean wrapLongWords) {
+        return wrap(str, wrapLength, newLineStr, wrapLongWords, " ");
+    }
+
+    /**
+     * Wraps a single line of text, identifying words by {@code wrapOn}.
+     *
+     * <p>Leading spaces on a new line are stripped.
+     * Trailing spaces are not stripped.</p>
+     *
+     * <table border="1">
+     *  <caption>Examples</caption>
+     *  <tr>
+     *   <th>input</th>
+     *   <th>wrapLength</th>
+     *   <th>newLineString</th>
+     *   <th>wrapLongWords</th>
+     *   <th>wrapOn</th>
+     *   <th>result</th>
+     *  </tr>
+     *  <tr>
+     *   <td>null</td>
+     *   <td>*</td>
+     *   <td>*</td>
+     *   <td>true/false</td>
+     *   <td>*</td>
+     *   <td>null</td>
+     *  </tr>
+     *  <tr>
+     *   <td>""</td>
+     *   <td>*</td>
+     *   <td>*</td>
+     *   <td>true/false</td>
+     *   <td>*</td>
+     *   <td>""</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>true/false</td>
+     *   <td>" "</td>
+     *   <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>"&lt;br /&gt;"</td>
+     *   <td>true/false</td>
+     *   <td>" "</td>
+     *   <td>"Here is one line of&lt;br /&gt;text that is going&lt;br /&gt;
+     *   to be wrapped after&lt;br /&gt;20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
+     *   <td>20</td>
+     *   <td>null</td>
+     *   <td>true/false</td>
+     *   <td>" "</td>
+     *   <td>"Here is one line of" + systemNewLine + "text that is going"
+     *   + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>false</td>
+     *   <td>" "</td>
+     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>true</td>
+     *   <td>" "</td>
+     *   <td>"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"</td>
+     *  </tr>
+     *  <tr>
+     *   <td>"flammable/inflammable"</td>
+     *   <td>20</td>
+     *   <td>"\n"</td>
+     *   <td>true</td>
+     *   <td>"/"</td>
+     *   <td>"flammable\ninflammable"</td>
+     *  </tr>
+     * </table>
+     * @param str  the String to be word wrapped, may be null
+     * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
+     * @param newLineStr  the string to insert for a new line,
+     *  {@code null} uses the system property line separator
+     * @param wrapLongWords  true if long words (such as URLs) should be wrapped
+     * @param wrapOn regex expression to be used as a breakable characters,
+     *               if blank string is provided a space character will be used
+     * @return a line with newlines inserted, {@code null} if null input
+     */
+    public static String wrap(final String str,
+                              int wrapLength,
+                              String newLineStr,
+                              final boolean wrapLongWords,
+                              String wrapOn) {
+        if (str == null) {
+            return null;
+        }
+        if (newLineStr == null) {
+            newLineStr = System.lineSeparator();
+        }
+        if (wrapLength < 1) {
+            wrapLength = 1;
+        }
+        if (StringUtils.isBlank(wrapOn)) {
+            wrapOn = " ";
         }
-        final Set<Integer> delimiterSet = generateDelimiterSet(delimiters);
-        final int strLen = str.length();
-        final int[] newCodePoints = new int[strLen / 2 + 1];
-        int count = 0;
-        boolean lastWasGap = true;
-        for (int i = 0; i < strLen;) {
-            final int codePoint = str.codePointAt(i);
+        final Pattern patternToWrapOn = Pattern.compile(wrapOn);
+        final int inputLineLength = str.length();
+        int offset = 0;
+        final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);
+        int matcherSize = -1;
 
-            if (delimiterSet.contains(codePoint) || (delimiters == null && Character.isWhitespace(codePoint))) {
-                lastWasGap = true;
-            } else if (lastWasGap) {
-                newCodePoints[count++] = codePoint;
-                lastWasGap = false;
+        while (offset < inputLineLength) {
+            int spaceToWrapAt = -1;
+            Matcher matcher = patternToWrapOn.matcher(str.substring(offset,
+                    Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength)));
+            if (matcher.find()) {
+                if (matcher.start() == 0) {
+                    matcherSize = matcher.end();
+                    if (matcherSize != 0) {
+                        offset += matcher.end();
+                        continue;
+                    }
+                    offset += 1;
+                }
+                spaceToWrapAt = matcher.start() + offset;
             }
 
-            i += Character.charCount(codePoint);
-        }
-        return new String(newCodePoints, 0, count);
-    }
-
-    /**
-     * Checks if the String contains all words in the given array.
-     *
-     * <p>
-     * A {@code null} String will return {@code false}. A {@code null}, zero
-     * length search array or if one element of array is null will return {@code false}.
-     * </p>
-     *
-     * <pre>
-     * WordUtils.containsAllWords(null, *)            = false
-     * WordUtils.containsAllWords("", *)              = false
-     * WordUtils.containsAllWords(*, null)            = false
-     * WordUtils.containsAllWords(*, [])              = false
-     * WordUtils.containsAllWords("abcd", "ab", "cd") = false
-     * WordUtils.containsAllWords("abc def", "def", "abc") = true
-     * </pre>
-     *
-     * @param word The CharSequence to check, may be null
-     * @param words The array of String words to search for, may be null
-     * @return {@code true} if all search words are found, {@code false} otherwise
-     */
-    public static boolean containsAllWords(final CharSequence word, final CharSequence... words) {
-        if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) {
-            return false;
-        }
-        for (final CharSequence w : words) {
-            if (StringUtils.isBlank(w)) {
-                return false;
-            }
-            final Pattern p = Pattern.compile(".*\\b" + w + "\\b.*");
-            if (!p.matcher(word).matches()) {
-                return false;
+            // only last line without leading spaces is left
+            if (inputLineLength - offset <= wrapLength) {
+                break;
             }
-        }
-        return true;
-    }
 
-    /**
-     * Is the character a delimiter.
-     *
-     * @param ch the character to check
-     * @param delimiters the delimiters
-     * @return true if it is a delimiter
-     * @deprecated as of 1.2 and will be removed in 2.0
-     */
-    @Deprecated
-    public static boolean isDelimiter(final char ch, final char[] delimiters) {
-        if (delimiters == null) {
-            return Character.isWhitespace(ch);
-        }
-        for (final char delimiter : delimiters) {
-            if (ch == delimiter) {
-                return true;
+            while (matcher.find()) {
+                spaceToWrapAt = matcher.start() + offset;
             }
-        }
-        return false;
-    }
 
-    /**
-     * Is the codePoint a delimiter.
-     *
-     * @param codePoint the codePint to check
-     * @param delimiters the delimiters
-     * @return true if it is a delimiter
-     * @deprecated as of 1.2 and will be removed in 2.0
-     */
-    @Deprecated
-    public static boolean isDelimiter(final int codePoint, final char[] delimiters) {
-        if (delimiters == null) {
-            return Character.isWhitespace(codePoint);
-        }
-        for (int index = 0; index < delimiters.length; index++) {
-            final int delimiterCodePoint = Character.codePointAt(delimiters, index);
-            if (delimiterCodePoint == codePoint) {
-                return true;
-            }
-        }
-        return false;
-    }
+            if (spaceToWrapAt >= offset) {
+                // normal case
+                wrappedLine.append(str, offset, spaceToWrapAt);
+                wrappedLine.append(newLineStr);
+                offset = spaceToWrapAt + 1;
 
-    /**
-     * Abbreviates the words nicely.
-     *
-     * <p>
-     * This method searches for the first space after the lower limit and abbreviates
-     * the String there. It will also append any String passed as a parameter
-     * to the end of the String. The upper limit can be specified to forcibly
-     * abbreviate a String.
-     * </p>
-     *
-     * @param str         the string to be abbreviated. If null is passed, null is returned.
-     *                    If the empty String is passed, the empty string is returned.
-     * @param lower       the lower limit; negative value is treated as zero.
-     * @param upper       the upper limit; specify -1 if no limit is desired.
-     *                    If the upper limit is lower than the lower limit, it will be
-     *                    adjusted to be the same as the lower limit.
-     * @param appendToEnd String to be appended to the end of the abbreviated string.
-     *                    This is appended ONLY if the string was indeed abbreviated.
-     *                    The append does not count towards the lower or upper limits.
-     * @return The abbreviated String.
-     *
-     * <pre>
-     * WordUtils.abbreviate("Now is the time for all good men", 0, 40, null));     = "Now"
-     * WordUtils.abbreviate("Now is the time for all good men", 10, 40, null));    = "Now is the"
-     * WordUtils.abbreviate("Now is the time for all good men", 20, 40, null));    = "Now is the time for all"
-     * WordUtils.abbreviate("Now is the time for all good men", 0, 40, ""));       = "Now"
-     * WordUtils.abbreviate("Now is the time for all good men", 10, 40, ""));      = "Now is the"
-     * WordUtils.abbreviate("Now is the time for all good men", 20, 40, ""));      = "Now is the time for all"
-     * WordUtils.abbreviate("Now is the time for all good men", 0, 40, " ..."));   = "Now ..."
-     * WordUtils.abbreviate("Now is the time for all good men", 10, 40, " ..."));  = "Now is the ..."
-     * WordUtils.abbreviate("Now is the time for all good men", 20, 40, " ..."));  = "Now is the time for all ..."
-     * WordUtils.abbreviate("Now is the time for all good men", 0, -1, ""));       = "Now"
-     * WordUtils.abbreviate("Now is the time for all good men", 10, -1, ""));      = "Now is the"
-     * WordUtils.abbreviate("Now is the time for all good men", 20, -1, ""));      = "Now is the time for all"
-     * WordUtils.abbreviate("Now is the time for all good men", 50, -1, ""));      = "Now is the time for all good men"
-     * WordUtils.abbreviate("Now is the time for all good men", 1000, -1, ""));    = "Now is the time for all good men"
-     * WordUtils.abbreviate("Now is the time for all good men", 9, -10, null));    = IllegalArgumentException
-     * WordUtils.abbreviate("Now is the time for all good men", 10, 5, null));     = IllegalArgumentException
-     * </pre>
-     */
-    public static String abbreviate(final String str, int lower, int upper, final String appendToEnd) {
-        Validate.isTrue(upper >= -1, "upper value cannot be less than -1");
-        Validate.isTrue(upper >= lower || upper == -1, "upper value is less than lower value");
-        if (StringUtils.isEmpty(str)) {
-            return str;
-        }
+            } else {
+                // really long word or URL
+                if (wrapLongWords) {
+                    if (matcherSize == 0) {
+                        offset--;
+                    }
+                    // wrap really long word one line at a time
+                    wrappedLine.append(str, offset, wrapLength + offset);
+                    wrappedLine.append(newLineStr);
+                    offset += wrapLength;
+                    matcherSize = -1;
+                } else {
+                    // do not wrap really long word, just extend beyond limit
+                    matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength));
+                    if (matcher.find()) {
+                        matcherSize = matcher.end() - matcher.start();
+                        spaceToWrapAt = matcher.start() + offset + wrapLength;
+                    }
 
-        // if the lower value is greater than the length of the string,
-        // set to the length of the string
-        if (lower > str.length()) {
-            lower = str.length();
+                    if (spaceToWrapAt >= 0) {
+                        if (matcherSize == 0 && offset != 0) {
+                            offset--;
+                        }
+                        wrappedLine.append(str, offset, spaceToWrapAt);
+                        wrappedLine.append(newLineStr);
+                        offset = spaceToWrapAt + 1;
+                    } else {
+                        if (matcherSize == 0 && offset != 0) {
+                            offset--;
+                        }
+                        wrappedLine.append(str, offset, str.length());
+                        offset = inputLineLength;
+                        matcherSize = -1;
+                    }
+                }
+            }
         }
 
-        // if the upper value is -1 (i.e. no limit) or is greater
-        // than the length of the string, set to the length of the string
-        if (upper == -1 || upper > str.length()) {
-            upper = str.length();
+        if (matcherSize == 0 && offset < inputLineLength) {
+            offset--;
         }
 
-        final StringBuilder result = new StringBuilder();
-        final int index = StringUtils.indexOf(str, " ", lower);
-        if (index == -1) {
-            result.append(str, 0, upper);
-            // only if abbreviation has occurred do we append the appendToEnd value
-            if (upper != str.length()) {
-                result.append(StringUtils.defaultString(appendToEnd));
-            }
-        } else if (index > upper) {
-            result.append(str, 0, upper);
-            result.append(StringUtils.defaultString(appendToEnd));
-        } else {
-            result.append(str, 0, index);
-            result.append(StringUtils.defaultString(appendToEnd));
-        }
+        // Whatever is left in line is short enough to just pass through
+        wrappedLine.append(str, offset, str.length());
 
-        return result.toString();
+        return wrappedLine.toString();
     }
 
     /**
-     * Converts an array of delimiters to a hash set of code points. Code point of space(32) is added as the default
-     * value if delimiters is null. The generated hash set provides O(1) lookup time.
+     * {@code WordUtils} instances should NOT be constructed in
+     * standard programming. Instead, the class should be used as
+     * {@code WordUtils.wrap("foo bar", 20);}.
      *
-     * @param delimiters set of characters to determine capitalization, null means whitespace
-     * @return Set<Integer>
+     * <p>This constructor is public to permit tools that require a JavaBean
+     * instance to operate.</p>
      */
-    private static Set<Integer> generateDelimiterSet(final char[] delimiters) {
-        final Set<Integer> delimiterHashSet = new HashSet<>();
-        if (delimiters == null || delimiters.length == 0) {
-            if (delimiters == null) {
-                delimiterHashSet.add(Character.codePointAt(new char[] {' '}, 0));
-            }
-
-            return delimiterHashSet;
-        }
-
-        for (int index = 0; index < delimiters.length; index++) {
-            delimiterHashSet.add(Character.codePointAt(delimiters, index));
-        }
-        return delimiterHashSet;
+    public WordUtils() {
     }
  }

[commons-text] 02/04: Sort members.

Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git

commit d1fde0d4f4e76798ccf541908134314a8c81d833
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Jul 24 11:18:17 2021 -0400

    Sort members.
---
 .../text/translate/CharSequenceTranslator.java     | 42 +++++-----
 .../commons/text/translate/CsvTranslators.java     | 32 ++++----
 .../text/translate/NumericEntityEscaper.java       | 66 +++++++--------
 .../text/translate/NumericEntityUnescaper.java     |  8 +-
 .../commons/text/translate/OctalUnescaper.java     | 40 ++++-----
 .../text/translate/SinglePassTranslator.java       | 20 ++---
 .../commons/text/translate/UnicodeEscaper.java     | 96 +++++++++++-----------
 7 files changed, 152 insertions(+), 152 deletions(-)

diff --git a/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java b/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java
index fa80a2b..109c768 100644
--- a/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java
+++ b/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java
@@ -41,18 +41,15 @@ public abstract class CharSequenceTranslator {
                                                  'C', 'D', 'E', 'F'};
 
     /**
-     * Translate a set of codepoints, represented by an int index into a CharSequence,
-     * into another set of codepoints. The number of codepoints consumed must be returned,
-     * and the only IOExceptions thrown must be from interacting with the Writer so that
-     * the top level API may reliably ignore StringWriter IOExceptions.
+     * Returns an upper case hexadecimal {@code String} for the given
+     * character.
      *
-     * @param input CharSequence that is being translated
-     * @param index int representing the current point of translation
-     * @param writer Writer to translate the text to
-     * @return int count of codepoints consumed
-     * @throws IOException if and only if the Writer produces an IOException
+     * @param codepoint The codepoint to convert.
+     * @return An upper case hexadecimal {@code String}
      */
-    public abstract int translate(CharSequence input, int index, Writer writer) throws IOException;
+    public static String hex(final int codepoint) {
+        return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
+    }
 
     /**
      * Helper for non-Writer usage.
@@ -74,6 +71,20 @@ public abstract class CharSequenceTranslator {
     }
 
     /**
+     * Translate a set of codepoints, represented by an int index into a CharSequence,
+     * into another set of codepoints. The number of codepoints consumed must be returned,
+     * and the only IOExceptions thrown must be from interacting with the Writer so that
+     * the top level API may reliably ignore StringWriter IOExceptions.
+     *
+     * @param input CharSequence that is being translated
+     * @param index int representing the current point of translation
+     * @param writer Writer to translate the text to
+     * @return int count of codepoints consumed
+     * @throws IOException if and only if the Writer produces an IOException
+     */
+    public abstract int translate(CharSequence input, int index, Writer writer) throws IOException;
+
+    /**
      * Translate an input onto a Writer. This is intentionally final as its algorithm is
      * tightly coupled with the abstract method of this class.
      *
@@ -127,15 +138,4 @@ public abstract class CharSequenceTranslator {
         return new AggregateTranslator(newArray);
     }
 
-    /**
-     * Returns an upper case hexadecimal {@code String} for the given
-     * character.
-     *
-     * @param codepoint The codepoint to convert.
-     * @return An upper case hexadecimal {@code String}
-     */
-    public static String hex(final int codepoint) {
-        return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
-    }
-
 }
diff --git a/src/main/java/org/apache/commons/text/translate/CsvTranslators.java b/src/main/java/org/apache/commons/text/translate/CsvTranslators.java
index d192b4d..84f786b 100644
--- a/src/main/java/org/apache/commons/text/translate/CsvTranslators.java
+++ b/src/main/java/org/apache/commons/text/translate/CsvTranslators.java
@@ -33,21 +33,6 @@ import org.apache.commons.lang3.StringUtils;
  */
 public final class CsvTranslators {
 
-    /** Comma character. */
-    private static final char CSV_DELIMITER = ',';
-    /** Quote character. */
-    private static final char CSV_QUOTE = '"';
-    /** Quote character converted to string. */
-    private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
-    /** Escaped quote string. */
-    private static final String CSV_ESCAPED_QUOTE_STR = CSV_QUOTE_STR + CSV_QUOTE_STR;
-    /** CSV key characters in an array. */
-    private static final char[] CSV_SEARCH_CHARS =
-            new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
-
-    /** Hidden constructor. */
-    private CsvTranslators() { }
-
     /**
      * Translator for escaping Comma Separated Values.
      */
@@ -66,7 +51,6 @@ public final class CsvTranslators {
             }
         }
     }
-
     /**
      * Translator for unescaping escaped Comma Separated Value entries.
      */
@@ -91,4 +75,20 @@ public final class CsvTranslators {
             }
         }
     }
+    /** Comma character. */
+    private static final char CSV_DELIMITER = ',';
+    /** Quote character. */
+    private static final char CSV_QUOTE = '"';
+    /** Quote character converted to string. */
+    private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
+
+    /** Escaped quote string. */
+    private static final String CSV_ESCAPED_QUOTE_STR = CSV_QUOTE_STR + CSV_QUOTE_STR;
+
+    /** CSV key characters in an array. */
+    private static final char[] CSV_SEARCH_CHARS =
+            new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
+
+    /** Hidden constructor. */
+    private CsvTranslators() { }
 }
diff --git a/src/main/java/org/apache/commons/text/translate/NumericEntityEscaper.java b/src/main/java/org/apache/commons/text/translate/NumericEntityEscaper.java
index b19dea2..693cb92 100644
--- a/src/main/java/org/apache/commons/text/translate/NumericEntityEscaper.java
+++ b/src/main/java/org/apache/commons/text/translate/NumericEntityEscaper.java
@@ -28,32 +28,14 @@ import org.apache.commons.lang3.Range;
  */
 public class NumericEntityEscaper extends CodePointTranslator {
 
-    /** whether to escape between the boundaries or outside them. */
-    private final boolean between;
-
-    /** range from lowest codepoint to highest codepoint. */
-    private final Range<Integer> range;
-
     /**
-     * Constructs a {@code NumericEntityEscaper} for the specified range. This is
-     * the underlying method for the other constructors/builders. The {@code below}
-     * and {@code above} boundaries are inclusive when {@code between} is
-     * {@code true} and exclusive when it is {@code false}.
+     * Constructs a {@code NumericEntityEscaper} above the specified value (exclusive).
      *
-     * @param below int value representing the lowest codepoint boundary
-     * @param above int value representing the highest codepoint boundary
-     * @param between whether to escape between the boundaries or outside them
-     */
-    private NumericEntityEscaper(final int below, final int above, final boolean between) {
-        this.range = Range.between(below, above);
-        this.between = between;
-    }
-
-    /**
-     * Constructs a {@code NumericEntityEscaper} for all characters.
+     * @param codepoint above which to escape
+     * @return The newly created {@code NumericEntityEscaper} instance
      */
-    public NumericEntityEscaper() {
-        this(0, Integer.MAX_VALUE, true);
+    public static NumericEntityEscaper above(final int codepoint) {
+        return outsideOf(0, codepoint);
     }
 
     /**
@@ -67,16 +49,6 @@ public class NumericEntityEscaper extends CodePointTranslator {
     }
 
     /**
-     * Constructs a {@code NumericEntityEscaper} above the specified value (exclusive).
-     *
-     * @param codepoint above which to escape
-     * @return The newly created {@code NumericEntityEscaper} instance
-     */
-    public static NumericEntityEscaper above(final int codepoint) {
-        return outsideOf(0, codepoint);
-    }
-
-    /**
      * Constructs a {@code NumericEntityEscaper} between the specified values (inclusive).
      *
      * @param codepointLow above which to escape
@@ -98,6 +70,34 @@ public class NumericEntityEscaper extends CodePointTranslator {
         return new NumericEntityEscaper(codepointLow, codepointHigh, false);
     }
 
+    /** whether to escape between the boundaries or outside them. */
+    private final boolean between;
+
+    /** range from lowest codepoint to highest codepoint. */
+    private final Range<Integer> range;
+
+    /**
+     * Constructs a {@code NumericEntityEscaper} for all characters.
+     */
+    public NumericEntityEscaper() {
+        this(0, Integer.MAX_VALUE, true);
+    }
+
+    /**
+     * Constructs a {@code NumericEntityEscaper} for the specified range. This is
+     * the underlying method for the other constructors/builders. The {@code below}
+     * and {@code above} boundaries are inclusive when {@code between} is
+     * {@code true} and exclusive when it is {@code false}.
+     *
+     * @param below int value representing the lowest codepoint boundary
+     * @param above int value representing the highest codepoint boundary
+     * @param between whether to escape between the boundaries or outside them
+     */
+    private NumericEntityEscaper(final int below, final int above, final boolean between) {
+        this.range = Range.between(below, above);
+        this.between = between;
+    }
+
     /**
      * {@inheritDoc}
      */
diff --git a/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java b/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
index 25f4d74..57f1b5e 100644
--- a/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
+++ b/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
@@ -34,10 +34,6 @@ import org.apache.commons.lang3.ArrayUtils;
  */
 public class NumericEntityUnescaper extends CharSequenceTranslator {
 
-    /** Default options. */
-    private static final EnumSet<OPTION> DEFAULT_OPTIONS = EnumSet
-        .copyOf(Collections.singletonList(OPTION.semiColonRequired));
-
     /** Enumerates NumericEntityUnescaper options for unescaping. */
     public enum OPTION {
 
@@ -57,6 +53,10 @@ public class NumericEntityUnescaper extends CharSequenceTranslator {
         errorIfNoSemiColon
     }
 
+    /** Default options. */
+    private static final EnumSet<OPTION> DEFAULT_OPTIONS = EnumSet
+        .copyOf(Collections.singletonList(OPTION.semiColonRequired));
+
     /** EnumSet of OPTIONS, given from the constructor, read-only. */
     private final EnumSet<OPTION> options;
 
diff --git a/src/main/java/org/apache/commons/text/translate/OctalUnescaper.java b/src/main/java/org/apache/commons/text/translate/OctalUnescaper.java
index 626ca41..23c33c8 100644
--- a/src/main/java/org/apache/commons/text/translate/OctalUnescaper.java
+++ b/src/main/java/org/apache/commons/text/translate/OctalUnescaper.java
@@ -32,6 +32,26 @@ import java.io.Writer;
 public class OctalUnescaper extends CharSequenceTranslator {
 
     /**
+     * Tests if the given char is an octal digit. Octal digits are the character representations of the digits 0 to 7.
+     *
+     * @param ch the char to check
+     * @return true if the given char is the character representation of one of the digits from 0 to 7
+     */
+    private boolean isOctalDigit(final char ch) {
+        return ch >= '0' && ch <= '7';
+    }
+
+    /**
+     * Tests if the given char is the character representation of one of the digit from 0 to 3.
+     *
+     * @param ch the char to check
+     * @return true if the given char is the character representation of one of the digits from 0 to 3
+     */
+    private boolean isZeroToThree(final char ch) {
+        return ch >= '0' && ch <= '3';
+    }
+
+    /**
      * {@inheritDoc}
      */
     @Override
@@ -58,24 +78,4 @@ public class OctalUnescaper extends CharSequenceTranslator {
         }
         return 0;
     }
-
-    /**
-     * Tests if the given char is an octal digit. Octal digits are the character representations of the digits 0 to 7.
-     *
-     * @param ch the char to check
-     * @return true if the given char is the character representation of one of the digits from 0 to 7
-     */
-    private boolean isOctalDigit(final char ch) {
-        return ch >= '0' && ch <= '7';
-    }
-
-    /**
-     * Tests if the given char is the character representation of one of the digit from 0 to 3.
-     *
-     * @param ch the char to check
-     * @return true if the given char is the character representation of one of the digits from 0 to 3
-     */
-    private boolean isZeroToThree(final char ch) {
-        return ch >= '0' && ch <= '3';
-    }
 }
diff --git a/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java b/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java
index d9f0012..db82bdb 100644
--- a/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java
+++ b/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java
@@ -25,6 +25,16 @@ import java.io.Writer;
  */
 abstract class SinglePassTranslator extends CharSequenceTranslator {
 
+    /**
+     * A utility method to be used in the {@link #translate(CharSequence, int, Writer)} method.
+     *
+     * @return The name of this or the extending class.
+     */
+    private String getClassName() {
+        final Class<? extends SinglePassTranslator> clazz = this.getClass();
+        return clazz.isAnonymousClass() ?  clazz.getName() : clazz.getSimpleName();
+    }
+
     @Override
     public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
         if (index != 0) {
@@ -38,16 +48,6 @@ abstract class SinglePassTranslator extends CharSequenceTranslator {
     }
 
     /**
-     * A utility method to be used in the {@link #translate(CharSequence, int, Writer)} method.
-     *
-     * @return The name of this or the extending class.
-     */
-    private String getClassName() {
-        final Class<? extends SinglePassTranslator> clazz = this.getClass();
-        return clazz.isAnonymousClass() ?  clazz.getName() : clazz.getSimpleName();
-    }
-
-    /**
      * Translates whole set of code points passed in input.
      *
      * @param input CharSequence that is being translated
diff --git a/src/main/java/org/apache/commons/text/translate/UnicodeEscaper.java b/src/main/java/org/apache/commons/text/translate/UnicodeEscaper.java
index 488ccc4..2892831 100644
--- a/src/main/java/org/apache/commons/text/translate/UnicodeEscaper.java
+++ b/src/main/java/org/apache/commons/text/translate/UnicodeEscaper.java
@@ -26,10 +26,52 @@ import java.io.Writer;
  */
 public class UnicodeEscaper extends CodePointTranslator {
 
+    /**
+     * Constructs a {@code UnicodeEscaper} above the specified value (exclusive).
+     *
+     * @param codepoint above which to escape
+     * @return The newly created {@code UnicodeEscaper} instance
+     */
+    public static UnicodeEscaper above(final int codepoint) {
+        return outsideOf(0, codepoint);
+    }
+    /**
+     * Constructs a {@code UnicodeEscaper} below the specified value (exclusive).
+     *
+     * @param codepoint below which to escape
+     * @return The newly created {@code UnicodeEscaper} instance
+     */
+    public static UnicodeEscaper below(final int codepoint) {
+        return outsideOf(codepoint, Integer.MAX_VALUE);
+    }
+    /**
+     * Constructs a {@code UnicodeEscaper} between the specified values (inclusive).
+     *
+     * @param codepointLow above which to escape
+     * @param codepointHigh below which to escape
+     * @return The newly created {@code UnicodeEscaper} instance
+     */
+    public static UnicodeEscaper between(final int codepointLow, final int codepointHigh) {
+        return new UnicodeEscaper(codepointLow, codepointHigh, true);
+    }
+
+    /**
+     * Constructs a {@code UnicodeEscaper} outside of the specified values (exclusive).
+     *
+     * @param codepointLow below which to escape
+     * @param codepointHigh above which to escape
+     * @return The newly created {@code UnicodeEscaper} instance
+     */
+    public static UnicodeEscaper outsideOf(final int codepointLow, final int codepointHigh) {
+        return new UnicodeEscaper(codepointLow, codepointHigh, false);
+    }
+
     /** int value representing the lowest codepoint boundary. */
     private final int below;
+
     /** int value representing the highest codepoint boundary. */
     private final int above;
+
     /** whether to escape between the boundaries or outside them. */
     private final boolean between;
 
@@ -58,45 +100,15 @@ public class UnicodeEscaper extends CodePointTranslator {
     }
 
     /**
-     * Constructs a {@code UnicodeEscaper} below the specified value (exclusive).
-     *
-     * @param codepoint below which to escape
-     * @return The newly created {@code UnicodeEscaper} instance
-     */
-    public static UnicodeEscaper below(final int codepoint) {
-        return outsideOf(codepoint, Integer.MAX_VALUE);
-    }
-
-    /**
-     * Constructs a {@code UnicodeEscaper} above the specified value (exclusive).
-     *
-     * @param codepoint above which to escape
-     * @return The newly created {@code UnicodeEscaper} instance
-     */
-    public static UnicodeEscaper above(final int codepoint) {
-        return outsideOf(0, codepoint);
-    }
-
-    /**
-     * Constructs a {@code UnicodeEscaper} outside of the specified values (exclusive).
+     * Converts the given codepoint to a hex string of the form {@code "\\uXXXX"}.
      *
-     * @param codepointLow below which to escape
-     * @param codepointHigh above which to escape
-     * @return The newly created {@code UnicodeEscaper} instance
-     */
-    public static UnicodeEscaper outsideOf(final int codepointLow, final int codepointHigh) {
-        return new UnicodeEscaper(codepointLow, codepointHigh, false);
-    }
-
-    /**
-     * Constructs a {@code UnicodeEscaper} between the specified values (inclusive).
+     * @param codepoint
+     *            a Unicode code point
+     * @return The hex string for the given codepoint
      *
-     * @param codepointLow above which to escape
-     * @param codepointHigh below which to escape
-     * @return The newly created {@code UnicodeEscaper} instance
      */
-    public static UnicodeEscaper between(final int codepointLow, final int codepointHigh) {
-        return new UnicodeEscaper(codepointLow, codepointHigh, true);
+    protected String toUtf16Escape(final int codepoint) {
+        return "\\u" + hex(codepoint);
     }
 
     /**
@@ -125,16 +137,4 @@ public class UnicodeEscaper extends CodePointTranslator {
         }
         return true;
     }
-
-    /**
-     * Converts the given codepoint to a hex string of the form {@code "\\uXXXX"}.
-     *
-     * @param codepoint
-     *            a Unicode code point
-     * @return The hex string for the given codepoint
-     *
-     */
-    protected String toUtf16Escape(final int codepoint) {
-        return "\\u" + hex(codepoint);
-    }
 }

[commons-text] 04/04: Sort members.

Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git

commit 04a79525d8cd7d7e00c78d3bd8c03c9230763d2a
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Jul 24 11:19:19 2021 -0400

    Sort members.
---
 .../apache/commons/text/numbers/DoubleFormat.java  | 722 ++++++++---------
 .../apache/commons/text/numbers/ParsedDecimal.java | 854 ++++++++++-----------
 2 files changed, 788 insertions(+), 788 deletions(-)

diff --git a/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java b/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java
index 5269a90..1522330 100644
--- a/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java
+++ b/src/main/java/org/apache/commons/text/numbers/DoubleFormat.java
@@ -145,23 +145,166 @@ public enum DoubleFormat {
      */
     MIXED(MixedDoubleFormat::new);
 
-    /** Function used to construct instances for this format type. */
-    private final Function<Builder, DoubleFunction<String>> factory;
-
     /**
-     * Constructs a new instance.
-     * @param factory function used to construct format instances
+     * Base class for standard double formatting classes.
      */
-    DoubleFormat(final Function<Builder, DoubleFunction<String>> factory) {
-        this.factory = factory;
-    }
+    private abstract static class AbstractDoubleFormat
+        implements DoubleFunction<String>, ParsedDecimal.FormatOptions {
 
-    /**
-     * Creates a {@link Builder} for building formatter functions for this format type.
-     * @return builder instance
-     */
-    public Builder builder() {
-        return new Builder(factory);
+        /** Maximum precision; 0 indicates no limit. */
+        private final int maxPrecision;
+
+        /** Minimum decimal exponent. */
+        private final int minDecimalExponent;
+
+        /** String representing positive infinity. */
+        private final String positiveInfinity;
+
+        /** String representing negative infinity. */
+        private final String negativeInfinity;
+
+        /** String representing NaN. */
+        private final String nan;
+
+        /** Flag determining if fraction placeholders should be used. */
+        private final boolean fractionPlaceholder;
+
+        /** Flag determining if signed zero strings are allowed. */
+        private final boolean signedZero;
+
+        /** String containing the digits 0-9. */
+        private final char[] digits;
+
+        /** Decimal separator character. */
+        private final char decimalSeparator;
+
+        /** Thousands grouping separator. */
+        private final char groupingSeparator;
+
+        /** Flag indicating if thousands should be grouped. */
+        private final boolean groupThousands;
+
+        /** Minus sign character. */
+        private final char minusSign;
+
+        /** Exponent separator character. */
+        private final char[] exponentSeparatorChars;
+
+        /** Flag indicating if exponent values should always be included, even if zero. */
+        private final boolean alwaysIncludeExponent;
+
+        /**
+         * Constructs a new instance.
+         * @param builder builder instance containing configuration values
+         */
+        AbstractDoubleFormat(final Builder builder) {
+            this.maxPrecision = builder.maxPrecision;
+            this.minDecimalExponent = builder.minDecimalExponent;
+
+            this.positiveInfinity = builder.infinity;
+            this.negativeInfinity = builder.minusSign + builder.infinity;
+            this.nan = builder.nan;
+
+            this.fractionPlaceholder = builder.fractionPlaceholder;
+            this.signedZero = builder.signedZero;
+            this.digits = builder.digits.toCharArray();
+            this.decimalSeparator = builder.decimalSeparator;
+            this.groupingSeparator = builder.groupingSeparator;
+            this.groupThousands = builder.groupThousands;
+            this.minusSign = builder.minusSign;
+            this.exponentSeparatorChars = builder.exponentSeparator.toCharArray();
+            this.alwaysIncludeExponent = builder.alwaysIncludeExponent;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public String apply(final double d) {
+            if (Double.isFinite(d)) {
+                return applyFinite(d);
+            } else if (Double.isInfinite(d)) {
+                return d > 0.0
+                        ? positiveInfinity
+                        : negativeInfinity;
+            }
+            return nan;
+        }
+
+        /**
+         * Returns a formatted string representation of the given finite value.
+         * @param d double value
+         */
+        private String applyFinite(final double d) {
+            final ParsedDecimal n = ParsedDecimal.from(d);
+
+            int roundExponent = Math.max(n.getExponent(), minDecimalExponent);
+            if (maxPrecision > 0) {
+                roundExponent = Math.max(n.getScientificExponent() - maxPrecision + 1, roundExponent);
+            }
+            n.round(roundExponent);
+
+            return applyFiniteInternal(n);
+        }
+
+        /**
+         * Returns a formatted representation of the given rounded decimal value to {@code dst}.
+         * @param val value to format
+         * @return a formatted representation of the given rounded decimal value to {@code dst}.
+         */
+        protected abstract String applyFiniteInternal(ParsedDecimal val);
+
+        /** {@inheritDoc} */
+        @Override
+        public char getDecimalSeparator() {
+            return decimalSeparator;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public char[] getDigits() {
+            return digits;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public char[] getExponentSeparatorChars() {
+            return exponentSeparatorChars;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public char getGroupingSeparator() {
+            return groupingSeparator;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public char getMinusSign() {
+            return minusSign;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public boolean isAlwaysIncludeExponent() {
+            return alwaysIncludeExponent;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public boolean isGroupThousands() {
+            return groupThousands;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public boolean isIncludeFractionPlaceholder() {
+            return fractionPlaceholder;
+        }
+
+        /** {@inheritDoc} */
+        @Override
+        public boolean isSignedZero() {
+            return signedZero;
+        }
     }
 
     /**
@@ -236,79 +379,6 @@ public enum DoubleFormat {
         }
 
         /**
-         * Sets the maximum number of significant decimal digits used in format
-         * results. A value of {@code 0} indicates no limit. The default value is {@code 0}.
-         * @param maxPrecision maximum precision
-         * @return this instance
-         */
-        public Builder maxPrecision(final int maxPrecision) {
-            this.maxPrecision = maxPrecision;
-            return this;
-        }
-
-        /**
-         * Sets the minimum decimal exponent for formatted strings. No digits with an
-         * absolute value of less than <code>10<sup>minDecimalExponent</sup></code> will
-         * be included in format results. If the number being formatted does not contain
-         * any such digits, then zero is returned. For example, if {@code minDecimalExponent}
-         * is set to {@code -2} and the number {@code 3.14159} is formatted, the plain
-         * format result will be {@code "3.14"}. If {@code 0.001} is formatted, then the
-         * result is the zero string.
-         * @param minDecimalExponent minimum decimal exponent
-         * @return this instance
-         */
-        public Builder minDecimalExponent(final int minDecimalExponent) {
-            this.minDecimalExponent = minDecimalExponent;
-            return this;
-        }
-
-        /**
-         * Sets the maximum decimal exponent for numbers formatted as plain decimal strings when
-         * using the {@link DoubleFormat#MIXED MIXED} format type. If the number being formatted
-         * has an absolute value less than <code>10<sup>plainFormatMaxDecimalExponent + 1</sup></code> and
-         * greater than or equal to <code>10<sup>plainFormatMinDecimalExponent</sup></code> after any
-         * necessary rounding, then the formatted result will use the {@link DoubleFormat#PLAIN PLAIN} format type.
-         * Otherwise, {@link DoubleFormat#SCIENTIFIC SCIENTIFIC} format will be used. For example,
-         * if this value is set to {@code 2}, the number {@code 999} will be formatted as {@code "999.0"}
-         * while {@code 1000} will be formatted as {@code "1.0E3"}.
-         *
-         * <p>The default value is {@value #DEFAULT_PLAIN_FORMAT_MAX_DECIMAL_EXPONENT}.
-         *
-         * <p>This value is ignored for formats other than {@link DoubleFormat#MIXED}.
-         * @param plainFormatMaxDecimalExponent maximum decimal exponent for values formatted as plain
-         *      strings when using the {@link DoubleFormat#MIXED MIXED} format type.
-         * @return this instance
-         * @see #plainFormatMinDecimalExponent(int)
-         */
-        public Builder plainFormatMaxDecimalExponent(final int plainFormatMaxDecimalExponent) {
-            this.plainFormatMaxDecimalExponent = plainFormatMaxDecimalExponent;
-            return this;
-        }
-
-        /**
-         * Sets the minimum decimal exponent for numbers formatted as plain decimal strings when
-         * using the {@link DoubleFormat#MIXED MIXED} format type. If the number being formatted
-         * has an absolute value less than <code>10<sup>plainFormatMaxDecimalExponent + 1</sup></code> and
-         * greater than or equal to <code>10<sup>plainFormatMinDecimalExponent</sup></code> after any
-         * necessary rounding, then the formatted result will use the {@link DoubleFormat#PLAIN PLAIN} format type.
-         * Otherwise, {@link DoubleFormat#SCIENTIFIC SCIENTIFIC} format will be used. For example,
-         * if this value is set to {@code -2}, the number {@code 0.01} will be formatted as {@code "0.01"}
-         * while {@code 0.0099} will be formatted as {@code "9.9E-3"}.
-         *
-         * <p>The default value is {@value #DEFAULT_PLAIN_FORMAT_MIN_DECIMAL_EXPONENT}.
-         *
-         * <p>This value is ignored for formats other than {@link DoubleFormat#MIXED}.
-         * @param plainFormatMinDecimalExponent maximum decimal exponent for values formatted as plain
-         *      strings when using the {@link DoubleFormat#MIXED MIXED} format type.
-         * @return this instance
-         * @see #plainFormatMinDecimalExponent(int)
-         */
-        public Builder plainFormatMinDecimalExponent(final int plainFormatMinDecimalExponent) {
-            this.plainFormatMinDecimalExponent = plainFormatMinDecimalExponent;
-            return this;
-        }
-
-        /**
          * Sets the flag determining whether or not the zero string may be returned with the minus
          * sign or if it will always be returned in the positive form. For example, if set to {@code true},
          * the string {@code "-0.0"} may be returned for some input numbers. If {@code false}, only {@code "0.0"}
@@ -323,46 +393,27 @@ public enum DoubleFormat {
         }
 
         /**
-         * Sets the string containing the digit characters 0-9, in that order. The
-         * default value is the string {@code "0123456789"}.
-         * @param digits string containing the digit characters 0-9
-         * @return this instance
-         * @throws NullPointerException if the argument is {@code null}
-         * @throws IllegalArgumentException if the argument does not have a length of exactly 10
-         */
-        public Builder digits(final String digits) {
-            Objects.requireNonNull(digits, "Digits string cannot be null");
-            if (digits.length() != DEFAULT_DECIMAL_DIGITS.length()) {
-                throw new IllegalArgumentException("Digits string must contain exactly "
-                        + DEFAULT_DECIMAL_DIGITS.length() + " characters.");
-            }
-
-            this.digits = digits;
-            return this;
-        }
-
-        /**
-         * Sets the flag determining whether or not a zero character is added in the fraction position
-         * when no fractional value is present. For example, if set to {@code true}, the number {@code 1} would
-         * be formatted as {@code "1.0"}. If {@code false}, it would be formatted as {@code "1"}. The default
-         * value is {@code true}.
-         * @param fractionPlaceholder if {@code true}, a zero character is placed in the fraction position when
-         *      no fractional value is present; if {@code false}, fractional digits are only included when needed
+         * Sets the flag indicating if an exponent value should always be included in the
+         * formatted value, even if the exponent value is zero. This property only applies
+         * to formats that use scientific notation, namely
+         * {@link DoubleFormat#SCIENTIFIC SCIENTIFIC},
+         * {@link DoubleFormat#ENGINEERING ENGINEERING}, and
+         * {@link DoubleFormat#MIXED MIXED}. The default value is {@code false}.
+         * @param alwaysIncludeExponent if {@code true}, exponents will always be included in formatted
+         *      output even if the exponent value is zero
          * @return this instance
          */
-        public Builder includeFractionPlaceholder(final boolean fractionPlaceholder) {
-            this.fractionPlaceholder = fractionPlaceholder;
+        public Builder alwaysIncludeExponent(final boolean alwaysIncludeExponent) {
+            this.alwaysIncludeExponent = alwaysIncludeExponent;
             return this;
         }
 
         /**
-         * Sets the character used as the minus sign.
-         * @param minusSign character to use as the minus sign
-         * @return this instance
+         * Builds a new double format function.
+         * @return format function
          */
-        public Builder minusSign(final char minusSign) {
-            this.minusSign = minusSign;
-            return this;
+        public DoubleFunction<String> build() {
+            return factory.apply(this);
         }
 
         /**
@@ -378,27 +429,21 @@ public enum DoubleFormat {
         }
 
         /**
-         * Sets the character used to separate groups of thousands. Default value is {@code ','}.
-         * @param groupingSeparator character used to separate groups of thousands
+         * Sets the string containing the digit characters 0-9, in that order. The
+         * default value is the string {@code "0123456789"}.
+         * @param digits string containing the digit characters 0-9
          * @return this instance
-         * @see #groupThousands(boolean)
+         * @throws NullPointerException if the argument is {@code null}
+         * @throws IllegalArgumentException if the argument does not have a length of exactly 10
          */
-        public Builder groupingSeparator(final char groupingSeparator) {
-            this.groupingSeparator = groupingSeparator;
-            return this;
-        }
+        public Builder digits(final String digits) {
+            Objects.requireNonNull(digits, "Digits string cannot be null");
+            if (digits.length() != DEFAULT_DECIMAL_DIGITS.length()) {
+                throw new IllegalArgumentException("Digits string must contain exactly "
+                        + DEFAULT_DECIMAL_DIGITS.length() + " characters.");
+            }
 
-        /**
-         * If set to {@code true}, thousands will be grouped with the
-         * {@link #groupingSeparator(char) grouping separator}. For example, if set to {@code true},
-         * the number {@code 1000} could be formatted as {@code "1,000"}. This property only applies
-         * to the {@link DoubleFormat#PLAIN PLAIN} format. Default value is {@code false}.
-         * @param groupThousands if {@code true}, thousands will be grouped
-         * @return this instance
-         * @see #groupingSeparator(char)
-         */
-        public Builder groupThousands(final boolean groupThousands) {
-            this.groupThousands = groupThousands;
+            this.digits = digits;
             return this;
         }
 
@@ -416,45 +461,6 @@ public enum DoubleFormat {
         }
 
         /**
-         * Sets the flag indicating if an exponent value should always be included in the
-         * formatted value, even if the exponent value is zero. This property only applies
-         * to formats that use scientific notation, namely
-         * {@link DoubleFormat#SCIENTIFIC SCIENTIFIC},
-         * {@link DoubleFormat#ENGINEERING ENGINEERING}, and
-         * {@link DoubleFormat#MIXED MIXED}. The default value is {@code false}.
-         * @param alwaysIncludeExponent if {@code true}, exponents will always be included in formatted
-         *      output even if the exponent value is zero
-         * @return this instance
-         */
-        public Builder alwaysIncludeExponent(final boolean alwaysIncludeExponent) {
-            this.alwaysIncludeExponent = alwaysIncludeExponent;
-            return this;
-        }
-
-        /**
-         * Sets the string used to represent infinity. For negative infinity, this string
-         * is prefixed with the {@link #minusSign(char) minus sign}.
-         * @param infinity string used to represent infinity
-         * @return this instance
-         * @throws NullPointerException if the argument is {@code null}
-         */
-        public Builder infinity(final String infinity) {
-            this.infinity = Objects.requireNonNull(infinity, "Infinity string cannot be null");
-            return this;
-        }
-
-        /**
-         * Sets the string used to represent {@link Double#NaN}.
-         * @param nan string used to represent {@link Double#NaN}
-         * @return this instance
-         * @throws NullPointerException if the argument is {@code null}
-         */
-        public Builder nan(final String nan) {
-            this.nan = Objects.requireNonNull(nan, "NaN string cannot be null");
-            return this;
-        }
-
-        /**
          * Configures this instance with the given format symbols. The following values
          * are set:
          * <ul>
@@ -481,219 +487,191 @@ public enum DoubleFormat {
                     .groupingSeparator(symbols.getGroupingSeparator())
                     .minusSign(symbols.getMinusSign())
                     .exponentSeparator(symbols.getExponentSeparator())
-                    .infinity(symbols.getInfinity())
-                    .nan(symbols.getNaN());
-        }
-
-        /**
-         * Gets a string containing the localized digits 0-9 for the given symbols object. The
-         * string is constructed by starting at the {@link DecimalFormatSymbols#getZeroDigit() zero digit}
-         * and adding the next 9 consecutive characters.
-         * @param symbols symbols object
-         * @return string containing the localized digits 0-9
-         */
-        private String getDigitString(final DecimalFormatSymbols symbols) {
-            final int zeroDelta = symbols.getZeroDigit() - DEFAULT_DECIMAL_DIGITS.charAt(0);
-
-            final char[] digitChars = new char[DEFAULT_DECIMAL_DIGITS.length()];
-            for (int i = 0; i < DEFAULT_DECIMAL_DIGITS.length(); ++i) {
-                digitChars[i] = (char) (DEFAULT_DECIMAL_DIGITS.charAt(i) + zeroDelta);
-            }
-
-            return String.valueOf(digitChars);
-        }
-
-        /**
-         * Builds a new double format function.
-         * @return format function
-         */
-        public DoubleFunction<String> build() {
-            return factory.apply(this);
-        }
-    }
-
-    /**
-     * Base class for standard double formatting classes.
-     */
-    private abstract static class AbstractDoubleFormat
-        implements DoubleFunction<String>, ParsedDecimal.FormatOptions {
-
-        /** Maximum precision; 0 indicates no limit. */
-        private final int maxPrecision;
-
-        /** Minimum decimal exponent. */
-        private final int minDecimalExponent;
-
-        /** String representing positive infinity. */
-        private final String positiveInfinity;
-
-        /** String representing negative infinity. */
-        private final String negativeInfinity;
-
-        /** String representing NaN. */
-        private final String nan;
-
-        /** Flag determining if fraction placeholders should be used. */
-        private final boolean fractionPlaceholder;
-
-        /** Flag determining if signed zero strings are allowed. */
-        private final boolean signedZero;
-
-        /** String containing the digits 0-9. */
-        private final char[] digits;
-
-        /** Decimal separator character. */
-        private final char decimalSeparator;
-
-        /** Thousands grouping separator. */
-        private final char groupingSeparator;
-
-        /** Flag indicating if thousands should be grouped. */
-        private final boolean groupThousands;
-
-        /** Minus sign character. */
-        private final char minusSign;
-
-        /** Exponent separator character. */
-        private final char[] exponentSeparatorChars;
-
-        /** Flag indicating if exponent values should always be included, even if zero. */
-        private final boolean alwaysIncludeExponent;
-
-        /**
-         * Constructs a new instance.
-         * @param builder builder instance containing configuration values
-         */
-        AbstractDoubleFormat(final Builder builder) {
-            this.maxPrecision = builder.maxPrecision;
-            this.minDecimalExponent = builder.minDecimalExponent;
-
-            this.positiveInfinity = builder.infinity;
-            this.negativeInfinity = builder.minusSign + builder.infinity;
-            this.nan = builder.nan;
-
-            this.fractionPlaceholder = builder.fractionPlaceholder;
-            this.signedZero = builder.signedZero;
-            this.digits = builder.digits.toCharArray();
-            this.decimalSeparator = builder.decimalSeparator;
-            this.groupingSeparator = builder.groupingSeparator;
-            this.groupThousands = builder.groupThousands;
-            this.minusSign = builder.minusSign;
-            this.exponentSeparatorChars = builder.exponentSeparator.toCharArray();
-            this.alwaysIncludeExponent = builder.alwaysIncludeExponent;
-        }
-
-        /** {@inheritDoc} */
-        @Override
-        public boolean isIncludeFractionPlaceholder() {
-            return fractionPlaceholder;
+                    .infinity(symbols.getInfinity())
+                    .nan(symbols.getNaN());
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public boolean isSignedZero() {
-            return signedZero;
-        }
+        /**
+         * Gets a string containing the localized digits 0-9 for the given symbols object. The
+         * string is constructed by starting at the {@link DecimalFormatSymbols#getZeroDigit() zero digit}
+         * and adding the next 9 consecutive characters.
+         * @param symbols symbols object
+         * @return string containing the localized digits 0-9
+         */
+        private String getDigitString(final DecimalFormatSymbols symbols) {
+            final int zeroDelta = symbols.getZeroDigit() - DEFAULT_DECIMAL_DIGITS.charAt(0);
 
-        /** {@inheritDoc} */
-        @Override
-        public char[] getDigits() {
-            return digits;
-        }
+            final char[] digitChars = new char[DEFAULT_DECIMAL_DIGITS.length()];
+            for (int i = 0; i < DEFAULT_DECIMAL_DIGITS.length(); ++i) {
+                digitChars[i] = (char) (DEFAULT_DECIMAL_DIGITS.charAt(i) + zeroDelta);
+            }
 
-        /** {@inheritDoc} */
-        @Override
-        public char getDecimalSeparator() {
-            return decimalSeparator;
+            return String.valueOf(digitChars);
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public char getGroupingSeparator() {
-            return groupingSeparator;
+        /**
+         * Sets the character used to separate groups of thousands. Default value is {@code ','}.
+         * @param groupingSeparator character used to separate groups of thousands
+         * @return this instance
+         * @see #groupThousands(boolean)
+         */
+        public Builder groupingSeparator(final char groupingSeparator) {
+            this.groupingSeparator = groupingSeparator;
+            return this;
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public boolean isGroupThousands() {
-            return groupThousands;
+        /**
+         * If set to {@code true}, thousands will be grouped with the
+         * {@link #groupingSeparator(char) grouping separator}. For example, if set to {@code true},
+         * the number {@code 1000} could be formatted as {@code "1,000"}. This property only applies
+         * to the {@link DoubleFormat#PLAIN PLAIN} format. Default value is {@code false}.
+         * @param groupThousands if {@code true}, thousands will be grouped
+         * @return this instance
+         * @see #groupingSeparator(char)
+         */
+        public Builder groupThousands(final boolean groupThousands) {
+            this.groupThousands = groupThousands;
+            return this;
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public char getMinusSign() {
-            return minusSign;
+        /**
+         * Sets the flag determining whether or not a zero character is added in the fraction position
+         * when no fractional value is present. For example, if set to {@code true}, the number {@code 1} would
+         * be formatted as {@code "1.0"}. If {@code false}, it would be formatted as {@code "1"}. The default
+         * value is {@code true}.
+         * @param fractionPlaceholder if {@code true}, a zero character is placed in the fraction position when
+         *      no fractional value is present; if {@code false}, fractional digits are only included when needed
+         * @return this instance
+         */
+        public Builder includeFractionPlaceholder(final boolean fractionPlaceholder) {
+            this.fractionPlaceholder = fractionPlaceholder;
+            return this;
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public char[] getExponentSeparatorChars() {
-            return exponentSeparatorChars;
+        /**
+         * Sets the string used to represent infinity. For negative infinity, this string
+         * is prefixed with the {@link #minusSign(char) minus sign}.
+         * @param infinity string used to represent infinity
+         * @return this instance
+         * @throws NullPointerException if the argument is {@code null}
+         */
+        public Builder infinity(final String infinity) {
+            this.infinity = Objects.requireNonNull(infinity, "Infinity string cannot be null");
+            return this;
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public boolean isAlwaysIncludeExponent() {
-            return alwaysIncludeExponent;
+        /**
+         * Sets the maximum number of significant decimal digits used in format
+         * results. A value of {@code 0} indicates no limit. The default value is {@code 0}.
+         * @param maxPrecision maximum precision
+         * @return this instance
+         */
+        public Builder maxPrecision(final int maxPrecision) {
+            this.maxPrecision = maxPrecision;
+            return this;
         }
 
-        /** {@inheritDoc} */
-        @Override
-        public String apply(final double d) {
-            if (Double.isFinite(d)) {
-                return applyFinite(d);
-            } else if (Double.isInfinite(d)) {
-                return d > 0.0
-                        ? positiveInfinity
-                        : negativeInfinity;
-            }
-            return nan;
+        /**
+         * Sets the minimum decimal exponent for formatted strings. No digits with an
+         * absolute value of less than <code>10<sup>minDecimalExponent</sup></code> will
+         * be included in format results. If the number being formatted does not contain
+         * any such digits, then zero is returned. For example, if {@code minDecimalExponent}
+         * is set to {@code -2} and the number {@code 3.14159} is formatted, the plain
+         * format result will be {@code "3.14"}. If {@code 0.001} is formatted, then the
+         * result is the zero string.
+         * @param minDecimalExponent minimum decimal exponent
+         * @return this instance
+         */
+        public Builder minDecimalExponent(final int minDecimalExponent) {
+            this.minDecimalExponent = minDecimalExponent;
+            return this;
         }
 
         /**
-         * Returns a formatted string representation of the given finite value.
-         * @param d double value
+         * Sets the character used as the minus sign.
+         * @param minusSign character to use as the minus sign
+         * @return this instance
          */
-        private String applyFinite(final double d) {
-            final ParsedDecimal n = ParsedDecimal.from(d);
+        public Builder minusSign(final char minusSign) {
+            this.minusSign = minusSign;
+            return this;
+        }
 
-            int roundExponent = Math.max(n.getExponent(), minDecimalExponent);
-            if (maxPrecision > 0) {
-                roundExponent = Math.max(n.getScientificExponent() - maxPrecision + 1, roundExponent);
-            }
-            n.round(roundExponent);
+        /**
+         * Sets the string used to represent {@link Double#NaN}.
+         * @param nan string used to represent {@link Double#NaN}
+         * @return this instance
+         * @throws NullPointerException if the argument is {@code null}
+         */
+        public Builder nan(final String nan) {
+            this.nan = Objects.requireNonNull(nan, "NaN string cannot be null");
+            return this;
+        }
 
-            return applyFiniteInternal(n);
+        /**
+         * Sets the maximum decimal exponent for numbers formatted as plain decimal strings when
+         * using the {@link DoubleFormat#MIXED MIXED} format type. If the number being formatted
+         * has an absolute value less than <code>10<sup>plainFormatMaxDecimalExponent + 1</sup></code> and
+         * greater than or equal to <code>10<sup>plainFormatMinDecimalExponent</sup></code> after any
+         * necessary rounding, then the formatted result will use the {@link DoubleFormat#PLAIN PLAIN} format type.
+         * Otherwise, {@link DoubleFormat#SCIENTIFIC SCIENTIFIC} format will be used. For example,
+         * if this value is set to {@code 2}, the number {@code 999} will be formatted as {@code "999.0"}
+         * while {@code 1000} will be formatted as {@code "1.0E3"}.
+         *
+         * <p>The default value is {@value #DEFAULT_PLAIN_FORMAT_MAX_DECIMAL_EXPONENT}.
+         *
+         * <p>This value is ignored for formats other than {@link DoubleFormat#MIXED}.
+         * @param plainFormatMaxDecimalExponent maximum decimal exponent for values formatted as plain
+         *      strings when using the {@link DoubleFormat#MIXED MIXED} format type.
+         * @return this instance
+         * @see #plainFormatMinDecimalExponent(int)
+         */
+        public Builder plainFormatMaxDecimalExponent(final int plainFormatMaxDecimalExponent) {
+            this.plainFormatMaxDecimalExponent = plainFormatMaxDecimalExponent;
+            return this;
         }
 
         /**
-         * Returns a formatted representation of the given rounded decimal value to {@code dst}.
-         * @param val value to format
-         * @return a formatted representation of the given rounded decimal value to {@code dst}.
+         * Sets the minimum decimal exponent for numbers formatted as plain decimal strings when
+         * using the {@link DoubleFormat#MIXED MIXED} format type. If the number being formatted
+         * has an absolute value less than <code>10<sup>plainFormatMaxDecimalExponent + 1</sup></code> and
+         * greater than or equal to <code>10<sup>plainFormatMinDecimalExponent</sup></code> after any
+         * necessary rounding, then the formatted result will use the {@link DoubleFormat#PLAIN PLAIN} format type.
+         * Otherwise, {@link DoubleFormat#SCIENTIFIC SCIENTIFIC} format will be used. For example,
+         * if this value is set to {@code -2}, the number {@code 0.01} will be formatted as {@code "0.01"}
+         * while {@code 0.0099} will be formatted as {@code "9.9E-3"}.
+         *
+         * <p>The default value is {@value #DEFAULT_PLAIN_FORMAT_MIN_DECIMAL_EXPONENT}.
+         *
+         * <p>This value is ignored for formats other than {@link DoubleFormat#MIXED}.
+         * @param plainFormatMinDecimalExponent maximum decimal exponent for values formatted as plain
+         *      strings when using the {@link DoubleFormat#MIXED MIXED} format type.
+         * @return this instance
+         * @see #plainFormatMinDecimalExponent(int)
          */
-        protected abstract String applyFiniteInternal(ParsedDecimal val);
+        public Builder plainFormatMinDecimalExponent(final int plainFormatMinDecimalExponent) {
+            this.plainFormatMinDecimalExponent = plainFormatMinDecimalExponent;
+            return this;
+        }
     }
 
     /**
-     * Format class that produces plain decimal strings that do not use
-     * scientific notation.
+     * Format class that uses engineering notation for all values.
      */
-    private static class PlainDoubleFormat extends AbstractDoubleFormat {
+    private static class EngineeringDoubleFormat extends AbstractDoubleFormat {
 
         /**
          * Constructs a new instance.
          * @param builder builder instance containing configuration values
          */
-        PlainDoubleFormat(final Builder builder) {
+        EngineeringDoubleFormat(final Builder builder) {
             super(builder);
         }
 
-        /**
-         * {@inheritDoc}
-         */
+        /** {@inheritDoc} */
         @Override
-        protected String applyFiniteInternal(final ParsedDecimal val) {
-            return val.toPlainString(this);
+        public String applyFiniteInternal(final ParsedDecimal val) {
+            return val.toEngineeringString(this);
         }
     }
 
@@ -733,42 +711,64 @@ public enum DoubleFormat {
     }
 
     /**
-     * Format class that uses scientific notation for all values.
+     * Format class that produces plain decimal strings that do not use
+     * scientific notation.
      */
-    private static class ScientificDoubleFormat extends AbstractDoubleFormat {
+    private static class PlainDoubleFormat extends AbstractDoubleFormat {
 
         /**
          * Constructs a new instance.
          * @param builder builder instance containing configuration values
          */
-        ScientificDoubleFormat(final Builder builder) {
+        PlainDoubleFormat(final Builder builder) {
             super(builder);
         }
 
-        /** {@inheritDoc} */
+        /**
+         * {@inheritDoc}
+         */
         @Override
-        public String applyFiniteInternal(final ParsedDecimal val) {
-            return val.toScientificString(this);
+        protected String applyFiniteInternal(final ParsedDecimal val) {
+            return val.toPlainString(this);
         }
     }
 
     /**
-     * Format class that uses engineering notation for all values.
+     * Format class that uses scientific notation for all values.
      */
-    private static class EngineeringDoubleFormat extends AbstractDoubleFormat {
+    private static class ScientificDoubleFormat extends AbstractDoubleFormat {
 
         /**
          * Constructs a new instance.
          * @param builder builder instance containing configuration values
          */
-        EngineeringDoubleFormat(final Builder builder) {
+        ScientificDoubleFormat(final Builder builder) {
             super(builder);
         }
 
         /** {@inheritDoc} */
         @Override
         public String applyFiniteInternal(final ParsedDecimal val) {
-            return val.toEngineeringString(this);
+            return val.toScientificString(this);
         }
     }
+
+    /** Function used to construct instances for this format type. */
+    private final Function<Builder, DoubleFunction<String>> factory;
+
+    /**
+     * Constructs a new instance.
+     * @param factory function used to construct format instances
+     */
+    DoubleFormat(final Function<Builder, DoubleFunction<String>> factory) {
+        this.factory = factory;
+    }
+
+    /**
+     * Creates a {@link Builder} for building formatter functions for this format type.
+     * @return builder instance
+     */
+    public Builder builder() {
+        return new Builder(factory);
+    }
 }
diff --git a/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java b/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java
index 05060e6..7581c0d 100644
--- a/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java
+++ b/src/main/java/org/apache/commons/text/numbers/ParsedDecimal.java
@@ -43,18 +43,10 @@ final class ParsedDecimal {
     interface FormatOptions {
 
         /**
-         * Return {@code true} if fraction placeholders (e.g., {@code ".0"} in {@code "1.0"})
-         * should be included.
-         * @return {@code true} if fraction placeholders should be included
-         */
-        boolean isIncludeFractionPlaceholder();
-
-        /**
-         * Return {@code true} if the string zero should be prefixed with the minus sign
-         * for negative zero values.
-         * @return {@code true} if the minus zero string should be allowed
+         * Get the decimal separator character.
+         * @return decimal separator character
          */
-        boolean isSignedZero();
+        char getDecimalSeparator();
 
         /**
          * Get an array containing the localized digit characters 0-9 in that order.
@@ -64,10 +56,10 @@ final class ParsedDecimal {
         char[] getDigits();
 
         /**
-         * Get the decimal separator character.
-         * @return decimal separator character
+         * Get the exponent separator as an array of characters.
+         * @return exponent separator as an array of characters
          */
-        char getDecimalSeparator();
+        char[] getExponentSeparatorChars();
 
         /**
          * Get the character used to separate thousands groupings.
@@ -76,29 +68,37 @@ final class ParsedDecimal {
         char getGroupingSeparator();
 
         /**
-         * Return {@code true} if thousands should be grouped.
-         * @return {@code true} if thousand should be grouped
-         */
-        boolean isGroupThousands();
-
-        /**
          * Get the minus sign character.
          * @return minus sign character
          */
         char getMinusSign();
 
         /**
-         * Get the exponent separator as an array of characters.
-         * @return exponent separator as an array of characters
-         */
-        char[] getExponentSeparatorChars();
-
-        /**
          * Return {@code true} if exponent values should always be included in
          * formatted output, even if the value is zero.
          * @return {@code true} if exponent values should always be included
          */
         boolean isAlwaysIncludeExponent();
+
+        /**
+         * Return {@code true} if thousands should be grouped.
+         * @return {@code true} if thousand should be grouped
+         */
+        boolean isGroupThousands();
+
+        /**
+         * Return {@code true} if fraction placeholders (e.g., {@code ".0"} in {@code "1.0"})
+         * should be included.
+         * @return {@code true} if fraction placeholders should be included
+         */
+        boolean isIncludeFractionPlaceholder();
+
+        /**
+         * Return {@code true} if the string zero should be prefixed with the minus sign
+         * for negative zero values.
+         * @return {@code true} if the minus zero string should be allowed
+         */
+        boolean isSignedZero();
     }
 
     /** Minus sign character. */
@@ -125,6 +125,106 @@ final class ParsedDecimal {
     /** Number that exponents in engineering format must be a multiple of. */
     private static final int ENG_EXPONENT_MOD = 3;
 
+    /**
+     * Gets the numeric value of the given digit character. No validation of the
+     * character type is performed.
+     * @param ch digit character
+     * @return numeric value of the digit character, ex: '1' = 1
+     */
+    private static int digitValue(final char ch) {
+        return ch - ZERO_CHAR;
+    }
+
+    /**
+     * Constructs a new instance from the given double value.
+     * @param d double value
+     * @return a new instance containing the parsed components of the given double value
+     * @throws IllegalArgumentException if {@code d} is {@code NaN} or infinite
+     */
+    public static ParsedDecimal from(final double d) {
+        if (!Double.isFinite(d)) {
+            throw new IllegalArgumentException("Double is not finite");
+        }
+
+        // Get the canonical string representation of the double value and parse
+        // it to extract the components of the decimal value. From the documentation
+        // of Double.toString() and the fact that d is finite, we are guaranteed the
+        // following:
+        // - the string will not be empty
+        // - it will contain exactly one decimal point character
+        // - all digit characters are in the ASCII range
+        final char[] strChars = Double.toString(d).toCharArray();
+
+        final boolean negative = strChars[0] == MINUS_CHAR;
+        final int digitStartIdx = negative ? 1 : 0;
+
+        final int[] digits = new int[strChars.length - digitStartIdx - 1];
+
+        boolean foundDecimalPoint = false;
+        int digitCount = 0;
+        int significantDigitCount = 0;
+        int decimalPos = 0;
+
+        int i;
+        for (i = digitStartIdx; i < strChars.length; ++i) {
+            final char ch = strChars[i];
+
+            if (ch == DECIMAL_SEP_CHAR) {
+                foundDecimalPoint = true;
+                decimalPos = digitCount;
+            } else if (ch == EXPONENT_CHAR) {
+                // no more mantissa digits
+                break;
+            } else if (ch != ZERO_CHAR || digitCount > 0) {
+                // this is either the first non-zero digit or one after it
+                final int val = digitValue(ch);
+                digits[digitCount++] = val;
+
+                if (val > 0) {
+                    significantDigitCount = digitCount;
+                }
+            } else if (foundDecimalPoint) {
+                // leading zero in a fraction; adjust the decimal position
+                --decimalPos;
+            }
+        }
+
+        if (digitCount > 0) {
+            // determine the exponent
+            final int explicitExponent = i < strChars.length
+                    ? parseExponent(strChars, i + 1)
+                    : 0;
+            final int exponent = explicitExponent + decimalPos - significantDigitCount;
+
+            return new ParsedDecimal(negative, digits, significantDigitCount, exponent);
+        }
+
+        // no non-zero digits, so value is zero
+        return new ParsedDecimal(negative, new int[] {0}, 1, 0);
+    }
+
+    /**
+     * Parses a double exponent value from {@code chars}, starting at the {@code start}
+     * index and continuing through the end of the array.
+     * @param chars character array to parse a double exponent value from
+     * @param start start index
+     * @return parsed exponent value
+     */
+    private static int parseExponent(final char[] chars, final int start) {
+        int i = start;
+        final boolean neg = chars[i] == MINUS_CHAR;
+        if (neg) {
+            ++i;
+        }
+
+        int exp = 0;
+        for (; i < chars.length; ++i) {
+            exp = (exp * DECIMAL_RADIX) + digitValue(chars[i]);
+        }
+
+        return neg ? -exp : exp;
+    }
+
     /** True if the value is negative. */
     final boolean negative;
 
@@ -159,244 +259,77 @@ final class ParsedDecimal {
     }
 
     /**
-     * Gets the exponent value. This exponent produces a floating point value with the
-     * correct magnitude when applied to the internal unsigned integer.
-     * @return exponent value
+     * Appends the given character to the output buffer.
+     * @param ch character to append
      */
-    public int getExponent() {
-        return exponent;
+    private void append(final char ch) {
+        outputChars[outputIdx++] = ch;
     }
 
     /**
-     * Get sthe exponent that would be used when representing this number in scientific
-     * notation (i.e., with a single non-zero digit in front of the decimal point).
-     * @return the exponent that would be used when representing this number in scientific
-     *      notation
+     * Appends the given character array directly to the output buffer.
+     * @param chars characters to append
      */
-    public int getScientificExponent() {
-        return digitCount + exponent - 1;
+    private void append(final char[] chars) {
+        for (final char c : chars) {
+            append(c);
+        }
     }
 
     /**
-     * Rounds the instance to the given decimal exponent position using
-     * {@link java.math.RoundingMode#HALF_EVEN half-even rounding}. For example, a value of {@code -2}
-     * will round the instance to the digit at the position 10<sup>-2</sup> (i.e. to the closest multiple of 0.01).
-     * @param roundExponent exponent defining the decimal place to round to
+     * Appends the fractional component of the number to the current output buffer.
+     * @param zeroCount number of zeros to add after the decimal point and before the
+     *      first significant digit
+     * @param startIdx significant digit start index
+     * @param opts format options
      */
-    public void round(final int roundExponent) {
-        if (roundExponent > exponent) {
-            final int max = digitCount + exponent;
+    private void appendFraction(final int zeroCount, final int startIdx, final FormatOptions opts) {
+        final char[] localizedDigits = opts.getDigits();
+        final char localizedZero = localizedDigits[0];
 
-            if (roundExponent < max) {
-                // rounding to a decimal place less than the max; set max precision
-                maxPrecision(max - roundExponent);
-            } else if (roundExponent == max && shouldRoundUp(0)) {
-                // rounding up directly on the max decimal place
-                setSingleDigitValue(1, roundExponent);
-            } else {
-                // change to zero
-                setSingleDigitValue(0, 0);
+        if (startIdx < digitCount) {
+            append(opts.getDecimalSeparator());
+
+            // add the zero prefix
+            for (int i = 0; i < zeroCount; ++i) {
+                append(localizedZero);
+            }
+
+            // add the fraction digits
+            for (int i = startIdx; i < digitCount; ++i) {
+                appendLocalizedDigit(digits[i], localizedDigits);
             }
+        } else if (opts.isIncludeFractionPlaceholder()) {
+            append(opts.getDecimalSeparator());
+            append(localizedZero);
         }
     }
 
     /**
-     * Ensures that this instance has <em>at most</em> the given number of significant digits
-     * (i.e. precision). If this instance already has a precision less than or equal
-     * to the argument, nothing is done. If the given precision requires a reduction in the number
-     * of digits, then the value is rounded using {@link java.math.RoundingMode#HALF_EVEN half-even rounding}.
-     * @param precision maximum number of significant digits to include
+     * Appends the localized representation of the digit {@code n} to the output buffer.
+     * @param n digit to append
+     * @param digitChars character array containing localized versions of the digits {@code 0-9}
+     *      in that order
      */
-    public void maxPrecision(final int precision) {
-        if (precision > 0 && precision < digitCount) {
-            if (shouldRoundUp(precision)) {
-                roundUp(precision);
-            } else {
-                truncate(precision);
-            }
-        }
+    private void appendLocalizedDigit(final int n, final char[] digitChars) {
+        append(digitChars[n]);
     }
 
     /**
-     * Returns a string representation of this value with no exponent field. Ex:
-     * <pre>
-     * 10 = "10.0"
-     * 1e-6 = "0.000001"
-     * 1e11 = "100000000000.0"
-     * </pre>
+     * Appends the whole number portion of this value to the output buffer. No thousands
+     * separators are added.
+     * @param wholeCount total number of digits required to the left of the decimal point
      * @param opts format options
-     * @return value in plain format
+     * @return number of digits from {@code digits} appended to the output buffer
+     * @see #appendWholeGrouped(int, FormatOptions)
      */
-    public String toPlainString(final FormatOptions opts) {
-        final int decimalPos = digitCount + exponent;
-        final int fractionZeroCount = decimalPos < 1
-                ? Math.abs(decimalPos)
-                : 0;
+    private int appendWhole(final int wholeCount, final FormatOptions opts) {
+        if (shouldIncludeMinus(opts)) {
+            append(opts.getMinusSign());
+        }
 
-        prepareOutput(getPlainStringSize(decimalPos, opts));
-
-        final int fractionStartIdx = opts.isGroupThousands()
-                ? appendWholeGrouped(decimalPos, opts)
-                : appendWhole(decimalPos, opts);
-
-        appendFraction(fractionZeroCount, fractionStartIdx, opts);
-
-        return outputString();
-    }
-
-    /**
-     * Returns a string representation of this value in scientific notation. Ex:
-     * <pre>
-     * 0 = "0.0"
-     * 10 = "1.0E1"
-     * 1e-6 = "1.0E-6"
-     * 1e11 = "1.0E11"
-     * </pre>
-     * @param opts format options
-     * @return value in scientific format
-     */
-    public String toScientificString(final FormatOptions opts) {
-        return toScientificString(1, opts);
-    }
-
-    /**
-     * Returns a string representation of this value in engineering notation. This
-     * is similar to {@link #toScientificString(FormatOptions) scientific notation}
-     * but with the exponent forced to be a multiple of 3, allowing easier alignment with SI prefixes.
-     * <pre>
-     * 0 = "0.0"
-     * 10 = "10.0"
-     * 1e-6 = "1.0E-6"
-     * 1e11 = "100.0E9"
-     * </pre>
-     * @param opts format options
-     * @return value in engineering format
-     */
-    public String toEngineeringString(final FormatOptions opts) {
-        final int decimalPos = 1 + Math.floorMod(getScientificExponent(), ENG_EXPONENT_MOD);
-        return toScientificString(decimalPos, opts);
-    }
-
-    /**
-     * Returns a string representation of the value in scientific notation using the
-     * given decimal point position.
-     * @param decimalPos decimal position relative to the {@code digits} array; this value
-     *      is expected to be greater than 0
-     * @param opts format options
-     * @return value in scientific format
-     */
-    private String toScientificString(final int decimalPos, final FormatOptions opts) {
-        final int targetExponent = digitCount + exponent - decimalPos;
-        final int absTargetExponent = Math.abs(targetExponent);
-        final boolean includeExponent = shouldIncludeExponent(targetExponent, opts);
-        final boolean negativeExponent = targetExponent < 0;
-
-        // determine the size of the full formatted string, including the number of
-        // characters needed for the exponent digits
-        int size = getDigitStringSize(decimalPos, opts);
-        int exponentDigitCount = 0;
-        if (includeExponent) {
-            exponentDigitCount = absTargetExponent > 0
-                    ? (int) Math.floor(Math.log10(absTargetExponent)) + 1
-                    : 1;
-
-            size += opts.getExponentSeparatorChars().length + exponentDigitCount;
-            if (negativeExponent) {
-                ++size;
-            }
-        }
-
-        prepareOutput(size);
-
-        // append the portion before the exponent field
-        final int fractionStartIdx = appendWhole(decimalPos, opts);
-        appendFraction(0, fractionStartIdx, opts);
-
-        if (includeExponent) {
-            // append the exponent field
-            append(opts.getExponentSeparatorChars());
-
-            if (negativeExponent) {
-                append(opts.getMinusSign());
-            }
-
-            // append the exponent digits themselves; compute the
-            // string representation directly and add it to the output
-            // buffer to avoid the overhead of Integer.toString()
-            final char[] localizedDigits = opts.getDigits();
-            int rem = absTargetExponent;
-            for (int i = size - 1; i >= outputIdx; --i) {
-                outputChars[i] = localizedDigits[rem % DECIMAL_RADIX];
-                rem /= DECIMAL_RADIX;
-            }
-            outputIdx = size;
-        }
-
-        return outputString();
-    }
-
-    /**
-     * Prepares the output buffer for a string of the given size.
-     * @param size buffer size
-     */
-    private void prepareOutput(final int size) {
-        outputChars = new char[size];
-        outputIdx = 0;
-    }
-
-    /**
-     * Gets the output buffer as a string.
-     * @return output buffer as a string
-     */
-    private String outputString() {
-        final String str = String.valueOf(outputChars);
-        outputChars = null;
-        return str;
-    }
-
-    /**
-     * Appends the given character to the output buffer.
-     * @param ch character to append
-     */
-    private void append(final char ch) {
-        outputChars[outputIdx++] = ch;
-    }
-
-    /**
-     * Appends the given character array directly to the output buffer.
-     * @param chars characters to append
-     */
-    private void append(final char[] chars) {
-        for (final char c : chars) {
-            append(c);
-        }
-    }
-
-    /**
-     * Appends the localized representation of the digit {@code n} to the output buffer.
-     * @param n digit to append
-     * @param digitChars character array containing localized versions of the digits {@code 0-9}
-     *      in that order
-     */
-    private void appendLocalizedDigit(final int n, final char[] digitChars) {
-        append(digitChars[n]);
-    }
-
-    /**
-     * Appends the whole number portion of this value to the output buffer. No thousands
-     * separators are added.
-     * @param wholeCount total number of digits required to the left of the decimal point
-     * @param opts format options
-     * @return number of digits from {@code digits} appended to the output buffer
-     * @see #appendWholeGrouped(int, FormatOptions)
-     */
-    private int appendWhole(final int wholeCount, final FormatOptions opts) {
-        if (shouldIncludeMinus(opts)) {
-            append(opts.getMinusSign());
-        }
-
-        final char[] localizedDigits = opts.getDigits();
-        final char localizedZero = localizedDigits[0];
+        final char[] localizedDigits = opts.getDigits();
+        final char localizedZero = localizedDigits[0];
 
         final int significantDigitCount = Math.max(0, Math.min(wholeCount, digitCount));
 
@@ -459,65 +392,6 @@ final class ParsedDecimal {
     }
 
     /**
-     * Returns {@code true} if a grouping separator should be added after the whole digit
-     * character at the given position.
-     * @param pos whole digit character position, with values starting at 1 and increasing
-     *      from right to left.
-     * @return {@code true} if a grouping separator should be added
-     */
-    private boolean requiresGroupingSeparatorAfterPosition(final int pos) {
-        return pos > 1 && (pos % THOUSANDS_GROUP_SIZE) == 1;
-    }
-
-    /**
-     * Appends the fractional component of the number to the current output buffer.
-     * @param zeroCount number of zeros to add after the decimal point and before the
-     *      first significant digit
-     * @param startIdx significant digit start index
-     * @param opts format options
-     */
-    private void appendFraction(final int zeroCount, final int startIdx, final FormatOptions opts) {
-        final char[] localizedDigits = opts.getDigits();
-        final char localizedZero = localizedDigits[0];
-
-        if (startIdx < digitCount) {
-            append(opts.getDecimalSeparator());
-
-            // add the zero prefix
-            for (int i = 0; i < zeroCount; ++i) {
-                append(localizedZero);
-            }
-
-            // add the fraction digits
-            for (int i = startIdx; i < digitCount; ++i) {
-                appendLocalizedDigit(digits[i], localizedDigits);
-            }
-        } else if (opts.isIncludeFractionPlaceholder()) {
-            append(opts.getDecimalSeparator());
-            append(localizedZero);
-        }
-    }
-
-    /**
-     * Gets the number of characters required to create a plain format representation
-     * of this value.
-     * @param decimalPos decimal position relative to the {@code digits} array
-     * @param opts format options
-     * @return number of characters in the plain string representation of this value,
-     *      created using the given parameters
-     */
-    private int getPlainStringSize(final int decimalPos, final FormatOptions opts) {
-        int size = getDigitStringSize(decimalPos, opts);
-
-        // adjust for groupings if needed
-        if (opts.isGroupThousands() && decimalPos > 0) {
-            size += (decimalPos - 1) / THOUSANDS_GROUP_SIZE;
-        }
-
-        return size;
-    }
-
-    /**
      * Gets the number of characters required for the digit portion of a string representation of
      * this value. This excludes any exponent or thousands groupings characters.
      * @param decimalPos decimal point position relative to the {@code digits} array
@@ -551,45 +425,120 @@ final class ParsedDecimal {
     }
 
     /**
-     * Returns {@code true} if formatted strings should include the minus sign, considering
-     * the value of this instance and the given format options.
-     * @param opts format options
-     * @return {@code true} if a minus sign should be included in the output
+     * Gets the exponent value. This exponent produces a floating point value with the
+     * correct magnitude when applied to the internal unsigned integer.
+     * @return exponent value
      */
-    private boolean shouldIncludeMinus(final FormatOptions opts) {
-        return negative && (opts.isSignedZero() || !isZero());
+    public int getExponent() {
+        return exponent;
     }
 
     /**
-     * Returns {@code true} if a formatted string with the given target exponent should include
-     * the exponent field.
-     * @param targetExponent exponent of the formatted result
+     * Gets the number of characters required to create a plain format representation
+     * of this value.
+     * @param decimalPos decimal position relative to the {@code digits} array
      * @param opts format options
-     * @return {@code true} if the formatted string should include the exponent field
+     * @return number of characters in the plain string representation of this value,
+     *      created using the given parameters
      */
-    private boolean shouldIncludeExponent(final int targetExponent, final FormatOptions opts) {
-        return targetExponent != 0 || opts.isAlwaysIncludeExponent();
+    private int getPlainStringSize(final int decimalPos, final FormatOptions opts) {
+        int size = getDigitStringSize(decimalPos, opts);
+
+        // adjust for groupings if needed
+        if (opts.isGroupThousands() && decimalPos > 0) {
+            size += (decimalPos - 1) / THOUSANDS_GROUP_SIZE;
+        }
+
+        return size;
     }
 
     /**
-     * Returns {@code true} if a rounding operation for the given number of digits should
-     * round up.
-     * @param count number of digits to round to; must be greater than zero and less
-     *      than the current number of digits
-     * @return {@code true} if a rounding operation for the given number of digits should
-     *      round up
+     * Get sthe exponent that would be used when representing this number in scientific
+     * notation (i.e., with a single non-zero digit in front of the decimal point).
+     * @return the exponent that would be used when representing this number in scientific
+     *      notation
      */
-    private boolean shouldRoundUp(final int count) {
-        // Round up in the following cases:
-        // 1. The digit after the last digit is greater than 5.
-        // 2. The digit after the last digit is 5 and there are additional (non-zero)
-        //      digits after it.
-        // 3. The digit after the last digit is 5, there are no additional digits afterward,
-        //      and the last digit is odd (half-even rounding).
-        final int digitAfterLast = digits[count];
+    public int getScientificExponent() {
+        return digitCount + exponent - 1;
+    }
 
-        return digitAfterLast > ROUND_CENTER || (digitAfterLast == ROUND_CENTER
-                && (count < digitCount - 1 || (digits[count - 1] % 2) != 0));
+    /**
+     * Returns {@code true} if this value is equal to zero. The sign field is ignored,
+     * meaning that this method will return {@code true} for both {@code +0} and {@code -0}.
+     * @return {@code true} if the value is equal to zero
+     */
+    boolean isZero() {
+        return digits[0] == 0;
+    }
+
+    /**
+     * Ensures that this instance has <em>at most</em> the given number of significant digits
+     * (i.e. precision). If this instance already has a precision less than or equal
+     * to the argument, nothing is done. If the given precision requires a reduction in the number
+     * of digits, then the value is rounded using {@link java.math.RoundingMode#HALF_EVEN half-even rounding}.
+     * @param precision maximum number of significant digits to include
+     */
+    public void maxPrecision(final int precision) {
+        if (precision > 0 && precision < digitCount) {
+            if (shouldRoundUp(precision)) {
+                roundUp(precision);
+            } else {
+                truncate(precision);
+            }
+        }
+    }
+
+    /**
+     * Gets the output buffer as a string.
+     * @return output buffer as a string
+     */
+    private String outputString() {
+        final String str = String.valueOf(outputChars);
+        outputChars = null;
+        return str;
+    }
+
+    /**
+     * Prepares the output buffer for a string of the given size.
+     * @param size buffer size
+     */
+    private void prepareOutput(final int size) {
+        outputChars = new char[size];
+        outputIdx = 0;
+    }
+
+    /**
+     * Returns {@code true} if a grouping separator should be added after the whole digit
+     * character at the given position.
+     * @param pos whole digit character position, with values starting at 1 and increasing
+     *      from right to left.
+     * @return {@code true} if a grouping separator should be added
+     */
+    private boolean requiresGroupingSeparatorAfterPosition(final int pos) {
+        return pos > 1 && (pos % THOUSANDS_GROUP_SIZE) == 1;
+    }
+
+    /**
+     * Rounds the instance to the given decimal exponent position using
+     * {@link java.math.RoundingMode#HALF_EVEN half-even rounding}. For example, a value of {@code -2}
+     * will round the instance to the digit at the position 10<sup>-2</sup> (i.e. to the closest multiple of 0.01).
+     * @param roundExponent exponent defining the decimal place to round to
+     */
+    public void round(final int roundExponent) {
+        if (roundExponent > exponent) {
+            final int max = digitCount + exponent;
+
+            if (roundExponent < max) {
+                // rounding to a decimal place less than the max; set max precision
+                maxPrecision(max - roundExponent);
+            } else if (roundExponent == max && shouldRoundUp(0)) {
+                // rounding up directly on the max decimal place
+                setSingleDigitValue(1, roundExponent);
+            } else {
+                // change to zero
+                setSingleDigitValue(0, 0);
+            }
+        }
     }
 
     /**
@@ -623,15 +572,6 @@ final class ParsedDecimal {
     }
 
     /**
-     * Returns {@code true} if this value is equal to zero. The sign field is ignored,
-     * meaning that this method will return {@code true} for both {@code +0} and {@code -0}.
-     * @return {@code true} if the value is equal to zero
-     */
-    boolean isZero() {
-        return digits[0] == 0;
-    }
-
-    /**
      * Sets the value of this instance to a single digit with the given exponent.
      * The sign of the value is retained.
      * @param digit digit value
@@ -644,120 +584,180 @@ final class ParsedDecimal {
     }
 
     /**
-     * Truncates the value to the given number of digits.
-     * @param count number of digits; must be greater than zero and less than
-     *      the current number of digits
+     * Returns {@code true} if a formatted string with the given target exponent should include
+     * the exponent field.
+     * @param targetExponent exponent of the formatted result
+     * @param opts format options
+     * @return {@code true} if the formatted string should include the exponent field
      */
-    private void truncate(final int count) {
-        // trim all trailing zero digits, making sure to leave
-        // at least one digit left
-        int nonZeroCount = count;
-        for (int i = count - 1;
-                i > 0 && digits[i] == 0;
-                --i) {
-            --nonZeroCount;
-        }
-        exponent += digitCount - nonZeroCount;
-        digitCount = nonZeroCount;
+    private boolean shouldIncludeExponent(final int targetExponent, final FormatOptions opts) {
+        return targetExponent != 0 || opts.isAlwaysIncludeExponent();
     }
 
     /**
-     * Constructs a new instance from the given double value.
-     * @param d double value
-     * @return a new instance containing the parsed components of the given double value
-     * @throws IllegalArgumentException if {@code d} is {@code NaN} or infinite
+     * Returns {@code true} if formatted strings should include the minus sign, considering
+     * the value of this instance and the given format options.
+     * @param opts format options
+     * @return {@code true} if a minus sign should be included in the output
      */
-    public static ParsedDecimal from(final double d) {
-        if (!Double.isFinite(d)) {
-            throw new IllegalArgumentException("Double is not finite");
-        }
-
-        // Get the canonical string representation of the double value and parse
-        // it to extract the components of the decimal value. From the documentation
-        // of Double.toString() and the fact that d is finite, we are guaranteed the
-        // following:
-        // - the string will not be empty
-        // - it will contain exactly one decimal point character
-        // - all digit characters are in the ASCII range
-        final char[] strChars = Double.toString(d).toCharArray();
+    private boolean shouldIncludeMinus(final FormatOptions opts) {
+        return negative && (opts.isSignedZero() || !isZero());
+    }
 
-        final boolean negative = strChars[0] == MINUS_CHAR;
-        final int digitStartIdx = negative ? 1 : 0;
+    /**
+     * Returns {@code true} if a rounding operation for the given number of digits should
+     * round up.
+     * @param count number of digits to round to; must be greater than zero and less
+     *      than the current number of digits
+     * @return {@code true} if a rounding operation for the given number of digits should
+     *      round up
+     */
+    private boolean shouldRoundUp(final int count) {
+        // Round up in the following cases:
+        // 1. The digit after the last digit is greater than 5.
+        // 2. The digit after the last digit is 5 and there are additional (non-zero)
+        //      digits after it.
+        // 3. The digit after the last digit is 5, there are no additional digits afterward,
+        //      and the last digit is odd (half-even rounding).
+        final int digitAfterLast = digits[count];
 
-        final int[] digits = new int[strChars.length - digitStartIdx - 1];
+        return digitAfterLast > ROUND_CENTER || (digitAfterLast == ROUND_CENTER
+                && (count < digitCount - 1 || (digits[count - 1] % 2) != 0));
+    }
 
-        boolean foundDecimalPoint = false;
-        int digitCount = 0;
-        int significantDigitCount = 0;
-        int decimalPos = 0;
+    /**
+     * Returns a string representation of this value in engineering notation. This
+     * is similar to {@link #toScientificString(FormatOptions) scientific notation}
+     * but with the exponent forced to be a multiple of 3, allowing easier alignment with SI prefixes.
+     * <pre>
+     * 0 = "0.0"
+     * 10 = "10.0"
+     * 1e-6 = "1.0E-6"
+     * 1e11 = "100.0E9"
+     * </pre>
+     * @param opts format options
+     * @return value in engineering format
+     */
+    public String toEngineeringString(final FormatOptions opts) {
+        final int decimalPos = 1 + Math.floorMod(getScientificExponent(), ENG_EXPONENT_MOD);
+        return toScientificString(decimalPos, opts);
+    }
 
-        int i;
-        for (i = digitStartIdx; i < strChars.length; ++i) {
-            final char ch = strChars[i];
+    /**
+     * Returns a string representation of this value with no exponent field. Ex:
+     * <pre>
+     * 10 = "10.0"
+     * 1e-6 = "0.000001"
+     * 1e11 = "100000000000.0"
+     * </pre>
+     * @param opts format options
+     * @return value in plain format
+     */
+    public String toPlainString(final FormatOptions opts) {
+        final int decimalPos = digitCount + exponent;
+        final int fractionZeroCount = decimalPos < 1
+                ? Math.abs(decimalPos)
+                : 0;
 
-            if (ch == DECIMAL_SEP_CHAR) {
-                foundDecimalPoint = true;
-                decimalPos = digitCount;
-            } else if (ch == EXPONENT_CHAR) {
-                // no more mantissa digits
-                break;
-            } else if (ch != ZERO_CHAR || digitCount > 0) {
-                // this is either the first non-zero digit or one after it
-                final int val = digitValue(ch);
-                digits[digitCount++] = val;
+        prepareOutput(getPlainStringSize(decimalPos, opts));
 
-                if (val > 0) {
-                    significantDigitCount = digitCount;
-                }
-            } else if (foundDecimalPoint) {
-                // leading zero in a fraction; adjust the decimal position
-                --decimalPos;
-            }
-        }
+        final int fractionStartIdx = opts.isGroupThousands()
+                ? appendWholeGrouped(decimalPos, opts)
+                : appendWhole(decimalPos, opts);
 
-        if (digitCount > 0) {
-            // determine the exponent
-            final int explicitExponent = i < strChars.length
-                    ? parseExponent(strChars, i + 1)
-                    : 0;
-            final int exponent = explicitExponent + decimalPos - significantDigitCount;
+        appendFraction(fractionZeroCount, fractionStartIdx, opts);
 
-            return new ParsedDecimal(negative, digits, significantDigitCount, exponent);
-        }
+        return outputString();
+    }
 
-        // no non-zero digits, so value is zero
-        return new ParsedDecimal(negative, new int[] {0}, 1, 0);
+    /**
+     * Returns a string representation of this value in scientific notation. Ex:
+     * <pre>
+     * 0 = "0.0"
+     * 10 = "1.0E1"
+     * 1e-6 = "1.0E-6"
+     * 1e11 = "1.0E11"
+     * </pre>
+     * @param opts format options
+     * @return value in scientific format
+     */
+    public String toScientificString(final FormatOptions opts) {
+        return toScientificString(1, opts);
     }
 
     /**
-     * Parses a double exponent value from {@code chars}, starting at the {@code start}
-     * index and continuing through the end of the array.
-     * @param chars character array to parse a double exponent value from
-     * @param start start index
-     * @return parsed exponent value
+     * Returns a string representation of the value in scientific notation using the
+     * given decimal point position.
+     * @param decimalPos decimal position relative to the {@code digits} array; this value
+     *      is expected to be greater than 0
+     * @param opts format options
+     * @return value in scientific format
      */
-    private static int parseExponent(final char[] chars, final int start) {
-        int i = start;
-        final boolean neg = chars[i] == MINUS_CHAR;
-        if (neg) {
-            ++i;
+    private String toScientificString(final int decimalPos, final FormatOptions opts) {
+        final int targetExponent = digitCount + exponent - decimalPos;
+        final int absTargetExponent = Math.abs(targetExponent);
+        final boolean includeExponent = shouldIncludeExponent(targetExponent, opts);
+        final boolean negativeExponent = targetExponent < 0;
+
+        // determine the size of the full formatted string, including the number of
+        // characters needed for the exponent digits
+        int size = getDigitStringSize(decimalPos, opts);
+        int exponentDigitCount = 0;
+        if (includeExponent) {
+            exponentDigitCount = absTargetExponent > 0
+                    ? (int) Math.floor(Math.log10(absTargetExponent)) + 1
+                    : 1;
+
+            size += opts.getExponentSeparatorChars().length + exponentDigitCount;
+            if (negativeExponent) {
+                ++size;
+            }
         }
 
-        int exp = 0;
-        for (; i < chars.length; ++i) {
-            exp = (exp * DECIMAL_RADIX) + digitValue(chars[i]);
+        prepareOutput(size);
+
+        // append the portion before the exponent field
+        final int fractionStartIdx = appendWhole(decimalPos, opts);
+        appendFraction(0, fractionStartIdx, opts);
+
+        if (includeExponent) {
+            // append the exponent field
+            append(opts.getExponentSeparatorChars());
+
+            if (negativeExponent) {
+                append(opts.getMinusSign());
+            }
+
+            // append the exponent digits themselves; compute the
+            // string representation directly and add it to the output
+            // buffer to avoid the overhead of Integer.toString()
+            final char[] localizedDigits = opts.getDigits();
+            int rem = absTargetExponent;
+            for (int i = size - 1; i >= outputIdx; --i) {
+                outputChars[i] = localizedDigits[rem % DECIMAL_RADIX];
+                rem /= DECIMAL_RADIX;
+            }
+            outputIdx = size;
         }
 
-        return neg ? -exp : exp;
+        return outputString();
     }
 
     /**
-     * Gets the numeric value of the given digit character. No validation of the
-     * character type is performed.
-     * @param ch digit character
-     * @return numeric value of the digit character, ex: '1' = 1
+     * Truncates the value to the given number of digits.
+     * @param count number of digits; must be greater than zero and less than
+     *      the current number of digits
      */
-    private static int digitValue(final char ch) {
-        return ch - ZERO_CHAR;
+    private void truncate(final int count) {
+        // trim all trailing zero digits, making sure to leave
+        // at least one digit left
+        int nonZeroCount = count;
+        for (int i = count - 1;
+                i > 0 && digits[i] == 0;
+                --i) {
+            --nonZeroCount;
+        }
+        exponent += digitCount - nonZeroCount;
+        digitCount = nonZeroCount;
     }
 }

[commons-text] 01/04: Sort members.

Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git

commit 2ff16ee48e1d94b2365ab5469b79f5aa76bfb976
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Jul 24 11:18:08 2021 -0400

    Sort members.
---
 .../apache/commons/text/diff/CommandVisitor.java   |  14 +-
 .../org/apache/commons/text/diff/EditCommand.java  |  18 +--
 .../org/apache/commons/text/diff/EditScript.java   |  42 ++---
 .../commons/text/diff/ReplacementsFinder.java      |  20 +--
 .../commons/text/diff/StringsComparator.java       | 180 ++++++++++-----------
 5 files changed, 137 insertions(+), 137 deletions(-)

diff --git a/src/main/java/org/apache/commons/text/diff/CommandVisitor.java b/src/main/java/org/apache/commons/text/diff/CommandVisitor.java
index 41a8697..6647bcc 100644
--- a/src/main/java/org/apache/commons/text/diff/CommandVisitor.java
+++ b/src/main/java/org/apache/commons/text/diff/CommandVisitor.java
@@ -124,6 +124,13 @@ package org.apache.commons.text.diff;
 public interface CommandVisitor<T> {
 
     /**
+     * Method called when a delete command is encountered.
+     *
+     * @param object object to delete (this object comes from the first sequence)
+     */
+    void visitDeleteCommand(T object);
+
+    /**
      * Method called when an insert command is encountered.
      *
      * @param object object to insert (this object comes from the second sequence)
@@ -137,11 +144,4 @@ public interface CommandVisitor<T> {
      */
     void visitKeepCommand(T object);
 
-    /**
-     * Method called when a delete command is encountered.
-     *
-     * @param object object to delete (this object comes from the first sequence)
-     */
-    void visitDeleteCommand(T object);
-
 }
diff --git a/src/main/java/org/apache/commons/text/diff/EditCommand.java b/src/main/java/org/apache/commons/text/diff/EditCommand.java
index 84cb1cf..65a40a6 100644
--- a/src/main/java/org/apache/commons/text/diff/EditCommand.java
+++ b/src/main/java/org/apache/commons/text/diff/EditCommand.java
@@ -67,15 +67,6 @@ public abstract class EditCommand<T> {
     }
 
     /**
-     * Gets the object associated with this command.
-     *
-     * @return The object on which the command is applied
-     */
-    protected T getObject() {
-        return object;
-    }
-
-    /**
      * Accepts a visitor.
      * <p>
      * This method is invoked for each commands belonging to
@@ -86,4 +77,13 @@ public abstract class EditCommand<T> {
      */
     public abstract void accept(CommandVisitor<T> visitor);
 
+    /**
+     * Gets the object associated with this command.
+     *
+     * @return The object on which the command is applied
+     */
+    protected T getObject() {
+        return object;
+    }
+
 }
diff --git a/src/main/java/org/apache/commons/text/diff/EditScript.java b/src/main/java/org/apache/commons/text/diff/EditScript.java
index 9e20c3c..60de713 100644
--- a/src/main/java/org/apache/commons/text/diff/EditScript.java
+++ b/src/main/java/org/apache/commons/text/diff/EditScript.java
@@ -66,13 +66,13 @@ public class EditScript<T> {
     }
 
     /**
-     * Appends a keep command to the script.
+     * Appends a delete command to the script.
      *
      * @param command  command to add
      */
-    public void append(final KeepCommand<T> command) {
+    public void append(final DeleteCommand<T> command) {
         commands.add(command);
-        ++lcsLength;
+        ++modifications;
     }
 
     /**
@@ -86,28 +86,13 @@ public class EditScript<T> {
     }
 
     /**
-     * Appends a delete command to the script.
+     * Appends a keep command to the script.
      *
      * @param command  command to add
      */
-    public void append(final DeleteCommand<T> command) {
+    public void append(final KeepCommand<T> command) {
         commands.add(command);
-        ++modifications;
-    }
-
-    /**
-     * Visits the script. The script implements the <em>visitor</em> design
-     * pattern, this method is the entry point to which the user supplies its
-     * own visitor, the script will be responsible to drive it through the
-     * commands in order and call the appropriate method as each command is
-     * encountered.
-     *
-     * @param visitor  the visitor that will visit all commands in turn
-     */
-    public void visit(final CommandVisitor<T> visitor) {
-        for (final EditCommand<T> command : commands) {
-            command.accept(visitor);
-        }
+        ++lcsLength;
     }
 
     /**
@@ -132,4 +117,19 @@ public class EditScript<T> {
         return modifications;
     }
 
+    /**
+     * Visits the script. The script implements the <em>visitor</em> design
+     * pattern, this method is the entry point to which the user supplies its
+     * own visitor, the script will be responsible to drive it through the
+     * commands in order and call the appropriate method as each command is
+     * encountered.
+     *
+     * @param visitor  the visitor that will visit all commands in turn
+     */
+    public void visit(final CommandVisitor<T> visitor) {
+        for (final EditCommand<T> command : commands) {
+            command.accept(visitor);
+        }
+    }
+
 }
diff --git a/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java b/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
index a701b12..1e6ede1 100644
--- a/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
+++ b/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
@@ -83,6 +83,16 @@ public class ReplacementsFinder<T> implements CommandVisitor<T> {
     }
 
     /**
+     * Add an object to the pending deletions set.
+     *
+     * @param object  object to delete
+     */
+    @Override
+    public void visitDeleteCommand(final T object) {
+        pendingDeletions.add(object);
+    }
+
+    /**
      * Add an object to the pending insertions set.
      *
      * @param object  object to insert
@@ -113,14 +123,4 @@ public class ReplacementsFinder<T> implements CommandVisitor<T> {
         }
     }
 
-    /**
-     * Add an object to the pending deletions set.
-     *
-     * @param object  object to delete
-     */
-    @Override
-    public void visitDeleteCommand(final T object) {
-        pendingDeletions.add(object);
-    }
-
 }
diff --git a/src/main/java/org/apache/commons/text/diff/StringsComparator.java b/src/main/java/org/apache/commons/text/diff/StringsComparator.java
index 90d53bb..477a8b4 100644
--- a/src/main/java/org/apache/commons/text/diff/StringsComparator.java
+++ b/src/main/java/org/apache/commons/text/diff/StringsComparator.java
@@ -53,6 +53,61 @@ package org.apache.commons.text.diff;
 public class StringsComparator {
 
     /**
+     * This class is a simple placeholder to hold the end part of a path
+     * under construction in a {@link StringsComparator StringsComparator}.
+     */
+    private static class Snake {
+
+        /** Start index. */
+        private final int start;
+
+        /** End index. */
+        private final int end;
+
+        /** Diagonal number. */
+        private final int diag;
+
+        /**
+         * Constructs a new instance of Snake with specified indices.
+         *
+         * @param start  start index of the snake
+         * @param end  end index of the snake
+         * @param diag  diagonal number
+         */
+        Snake(final int start, final int end, final int diag) {
+            this.start = start;
+            this.end   = end;
+            this.diag  = diag;
+        }
+
+        /**
+         * Gets the diagonal number of the snake.
+         *
+         * @return diagonal number of the snake
+         */
+        public int getDiag() {
+            return diag;
+        }
+
+        /**
+         * Gets the end index of the snake.
+         *
+         * @return end index of the snake
+         */
+        public int getEnd() {
+            return end;
+        }
+
+        /**
+         * Gets the start index of the snake.
+         *
+         * @return start index of the snake
+         */
+        public int getStart() {
+            return start;
+        }
+    }
+    /**
      * First character sequence.
      */
     private final String left;
@@ -64,6 +119,7 @@ public class StringsComparator {
      * Temporary array.
      */
     private final int[] vDown;
+
     /**
      * Temporary array.
      */
@@ -92,26 +148,6 @@ public class StringsComparator {
     }
 
     /**
-     * Gets the {@link EditScript} object.
-     * <p>
-     * It is guaranteed that the objects embedded in the {@link InsertCommand
-     * insert commands} come from the second sequence and that the objects
-     * embedded in either the {@link DeleteCommand delete commands} or
-     * {@link KeepCommand keep commands} come from the first sequence. This can
-     * be important if subclassing is used for some elements in the first
-     * sequence and the {@code equals} method is specialized.
-     * </p>
-     *
-     * @return The edit script resulting from the comparison of the two
-     *         sequences
-     */
-    public EditScript<Character> getScript() {
-        final EditScript<Character> script = new EditScript<>();
-        buildScript(0, left.length(), 0, right.length(), script);
-        return script;
-    }
-
-    /**
      * Builds an edit script.
      *
      * @param start1  the begin of the first sequence to be compared
@@ -161,6 +197,25 @@ public class StringsComparator {
     }
 
     /**
+     * Builds a snake.
+     *
+     * @param start  the value of the start of the snake
+     * @param diag  the value of the diagonal of the snake
+     * @param end1  the value of the end of the first sequence to be compared
+     * @param end2  the value of the end of the second sequence to be compared
+     * @return The snake built
+     */
+    private Snake buildSnake(final int start, final int diag, final int end1, final int end2) {
+        int end = start;
+        while (end - diag < end2
+                && end < end1
+                && left.charAt(end) == right.charAt(end - diag)) {
+            ++end;
+        }
+        return new Snake(start, end, diag);
+    }
+
+    /**
      * Gets the middle snake corresponding to two subsequences of the
      * main sequences.
      * <p>
@@ -251,78 +306,23 @@ public class StringsComparator {
     }
 
     /**
-     * Builds a snake.
+     * Gets the {@link EditScript} object.
+     * <p>
+     * It is guaranteed that the objects embedded in the {@link InsertCommand
+     * insert commands} come from the second sequence and that the objects
+     * embedded in either the {@link DeleteCommand delete commands} or
+     * {@link KeepCommand keep commands} come from the first sequence. This can
+     * be important if subclassing is used for some elements in the first
+     * sequence and the {@code equals} method is specialized.
+     * </p>
      *
-     * @param start  the value of the start of the snake
-     * @param diag  the value of the diagonal of the snake
-     * @param end1  the value of the end of the first sequence to be compared
-     * @param end2  the value of the end of the second sequence to be compared
-     * @return The snake built
-     */
-    private Snake buildSnake(final int start, final int diag, final int end1, final int end2) {
-        int end = start;
-        while (end - diag < end2
-                && end < end1
-                && left.charAt(end) == right.charAt(end - diag)) {
-            ++end;
-        }
-        return new Snake(start, end, diag);
-    }
-
-    /**
-     * This class is a simple placeholder to hold the end part of a path
-     * under construction in a {@link StringsComparator StringsComparator}.
+     * @return The edit script resulting from the comparison of the two
+     *         sequences
      */
-    private static class Snake {
-
-        /** Start index. */
-        private final int start;
-
-        /** End index. */
-        private final int end;
-
-        /** Diagonal number. */
-        private final int diag;
-
-        /**
-         * Constructs a new instance of Snake with specified indices.
-         *
-         * @param start  start index of the snake
-         * @param end  end index of the snake
-         * @param diag  diagonal number
-         */
-        Snake(final int start, final int end, final int diag) {
-            this.start = start;
-            this.end   = end;
-            this.diag  = diag;
-        }
-
-        /**
-         * Gets the start index of the snake.
-         *
-         * @return start index of the snake
-         */
-        public int getStart() {
-            return start;
-        }
-
-        /**
-         * Gets the end index of the snake.
-         *
-         * @return end index of the snake
-         */
-        public int getEnd() {
-            return end;
-        }
-
-        /**
-         * Gets the diagonal number of the snake.
-         *
-         * @return diagonal number of the snake
-         */
-        public int getDiag() {
-            return diag;
-        }
+    public EditScript<Character> getScript() {
+        final EditScript<Character> script = new EditScript<>();
+        buildScript(0, left.length(), 0, right.length(), script);
+        return script;
     }
 
 }