Class StringsPlume

java.lang.Object
org.plumelib.util.StringsPlume

public final class StringsPlume extends Object
Utility functions that manipulate Strings: replacement; prefixing and indentation; splitting and joining; quoting and escaping; whitespace; comparisons; StringTokenizer; debugging variants of toString; diagnostic output; miscellaneous.
  • Field Details

    • versionNumberRegex

      public static final @Regex String versionNumberRegex
      Matches a version number, of the form N.N or N.N.N, etc., where each N consists of digits.
      See Also:
    • versionNumberPattern

      public static final Pattern versionNumberPattern
      Matches a version number, of the form N.N or N.N.N, etc., where each N consists of digits.
  • Method Details

    • replacePrefix

      @SideEffectFree public static String replacePrefix(String target, String oldStr, String newStr)
      Returns the target with an occurrence of oldStr at the start replaced by newStr. Returns the target if it does not strt with oldStr.

      An alternative to this is to use regular expressions: target.replaceFirst("^" + Pattern.quote(oldStr), newStr)

      Parameters:
      target - the string to do replacement in
      oldStr - the prefix to replace
      newStr - the replacement
      Returns:
      the target with an occurrence of oldStr at the start replaced by newStr; returns the target if it does not start with oldStr
    • replaceSuffix

      @SideEffectFree public static String replaceSuffix(String target, String oldStr, String newStr)
      Returns the target with an occurrence of oldStr at the end replaced by newStr. Returns the target if it does not end with oldStr.

      An alternative to this is to use regular expressions: target.replaceLast(Pattern.quote(oldStr) + "$", newStr)

      Parameters:
      target - the string to do replacement in
      oldStr - the substring to replace
      newStr - the replacement
      Returns:
      the target with an occurrence of oldStr at the start replaced by newStr; returns the target if it does not start with oldStr
    • replaceAll

      @SideEffectFree public static String replaceAll(String s, Pattern regex, String replacement)
      Replaces every (non-overlapping) match for a regexp. Like String.replaceAll, but slightly more efficient because the regex has been pre-compiled.
      Parameters:
      s - a string in which to replace
      regex - a regular expression
      replacement - the replacement for each match of the regular expression
      Returns:
      the string, with each match for the regex replaced
    • prefixLines

      @SideEffectFree public static String prefixLines(String prefix, @Nullable Object o)
      Returns the printed represenation of a value, with each line prefixed by another string.
      Parameters:
      prefix - the prefix to place before each line
      o - the value to be printed
      Returns:
      the printed representation of o, with each line prefixed by the given prefix
    • prefixLinesExceptFirst

      @SideEffectFree public static String prefixLinesExceptFirst(String prefix, @Nullable Object o)
      Returns the printed represenation of a value, with each line (except the first) prefixed by another string.
      Parameters:
      prefix - the prefix to place before each line
      o - the value to be printed
      Returns:
      the printed representation of o, with each line (except the first) prefixed by the given prefix
    • indentLines

      @SideEffectFree public static String indentLines(@org.checkerframework.checker.index.qual.NonNegative int indent, @Nullable Object o)
      Returns the printed representation of a value, with each line indented by indent spaces.
      Parameters:
      indent - the number of spaces to indent
      o - the value whose printed representation string to increase indentation of
      Returns:
      the printed representation of o, with each line prefixed by indent space characters
    • indentLinesExceptFirst

      @SideEffectFree public static String indentLinesExceptFirst(@org.checkerframework.checker.index.qual.NonNegative int indent, @Nullable Object o)
      Returns the printed representation of a value, with each line (except the first) indented by indent spaces.
      Parameters:
      indent - the number of spaces to indent
      o - the value whose printed representation string to increase indentation of
      Returns:
      the printed representation of o, with each line (except the first) prefixed by indent space characters
    • splitLines

      @SideEffectFree @StaticallyExecutable public static String[] splitLines(String s)
      Returns an array of Strings, one for each line in the argument. The strings do not end with line separators. Always returns an array of length at least 1 (it might contain only the empty string). All common line separators (lf, cr, cr-lf) are supported. Note that a string that ends with a line separator will return an empty string as the last element of the array.

      It is probably better to use String.lines() rather than this method.

      Alternately, you could use firstLineSeparator(java.lang.String) and split on its return value.

      Parameters:
      s - the string to split
      Returns:
      an array of Strings, one for each line in the argument
    • firstLineSeparator

      @SideEffectFree public static @Nullable @Regex String firstLineSeparator(String s)
      Returns the first line separator in the given string, or null if the string contains none.
      Parameters:
      s - a string
      Returns:
      the first line separator in the given string
    • splitLinesRetainSeparators

      @SideEffectFree public static List<String> splitLinesRetainSeparators(String input)
      Splits a String into lines, keeping the line separator at the end of each substring.
      Parameters:
      input - the input String
      Returns:
      the split string
    • splitRetainSeparators

      @SideEffectFree public static List<String> splitRetainSeparators(String input, @Regex String regex)
      Splits a String according to a regex, keeping the separator at the end of each substring.
      Parameters:
      input - the input String
      regex - the regular expression upon which to split the input
      Returns:
      the split string
    • splitRetainSeparators

      @SideEffectFree public static List<String> splitRetainSeparators(String input, Pattern p)
      Splits a String according to a pattern, keeping the separator at the end of each substring.
      Parameters:
      input - the input String
      p - the pattern upon which to split the input
      Returns:
      the split string
    • join

      @SafeVarargs @SideEffectFree public static <T extends Object> String join(CharSequence delim, @Signed T... a)
      Concatenate the string representations of the array elements, placing the delimiter between them.

      This differs from the built-in String.join() method added in Java 8, in that this takes any arbitrary array but that method takes an array of CharSequences. Use the String method when the arguments are CharSequences.

      Type Parameters:
      T - the type of array elements
      Parameters:
      delim - delimiter to place between printed representations
      a - array of values to concatenate
      Returns:
      the concatenation of the string representations of the values, with the delimiter between
    • joinLines

      @SafeVarargs @SideEffectFree public static <T extends Object> String joinLines(@Signed T... a)
      Concatenate the string representations of the objects, placing the system-specific line separator between them.
      Type Parameters:
      T - the type of array elements
      Parameters:
      a - array of values to whose string representation to concatenate
      Returns:
      the concatenation of the string representations of the values, each on its own line
    • join

      @SideEffectFree public static String join(CharSequence delim, Iterable<? extends @Signed @PolyNull Object> v)
      Concatenate the string representations of the objects, placing the delimiter between them.

      This differs from the String.join() method added in Java 8, in that this takes any Iterable but that method takes only Iterable<? extends CharSequence>.

      Parameters:
      delim - delimiter to place between printed representations
      v - collection of values to concatenate
      Returns:
      the concatenation of the string representations of the values, with the delimiter between
      See Also:
    • joinLines

      @SideEffectFree public static String joinLines(Iterable<? extends @Signed @PolyNull Object> v)
      Concatenate the string representations of the objects, placing the system-specific line separator between them.
      Parameters:
      v - list of values to concatenate
      Returns:
      the concatenation of the string representations of the values, each on its own line
      See Also:
    • escapeJava

      @SideEffectFree public static String escapeJava(String orig)
      Escapes a String so that it is expressible in a string literal in Java source code. By surrounding the return value with double quote marks, the result will be a Java string literal denoting the original string.

      Returns a new string only if any modifications were necessary.

      Compared to the `escapeJava` method in Apache Commons Text StringEscapeUtils, this one correctly handles non-printable ASCII characters.

      Parameters:
      orig - string to quote
      Returns:
      quoted version of orig
    • escapeJava

      @Deprecated @SideEffectFree public static String escapeJava(Character ch)
      Like escapeJava(String), but for a single character. Note that this quotes its argument for inclusion in a string literal, not in a character literal.
      Parameters:
      ch - character to quote
      Returns:
      quoted version of ch
    • escapeJava

      @Deprecated @SideEffectFree public static String escapeJava(char c)
      Like escapeJava(String), but for a single character. Note that this quotes its argument for inclusion in a string literal, not in a character literal.
      Parameters:
      c - character to quote
      Returns:
      quoted version of ch
    • charLiteral

      @SideEffectFree public static String charLiteral(Character ch)
      Given a character, returns a Java character literal denoting the character.
      Parameters:
      ch - character to quote
      Returns:
      quoted version of ch
    • charLiteral

      @SideEffectFree public static String charLiteral(char c)
      Given a character, returns a Java character literal denoting the character.
      Parameters:
      c - character to quote
      Returns:
      quoted version of ch
    • escapeNonASCII

      @SideEffectFree public static String escapeNonASCII(String orig)
      Escape unprintable characters in the target, following the usual Java backslash conventions, so that the result is sure to be printable ASCII. Returns a new string.
      Parameters:
      orig - string to quote
      Returns:
      quoted version of orig
    • unescapeJava

      @SideEffectFree public static String unescapeJava(String orig)
      Convert a string from Java source code format (with escape sequences) into the string it would represent at run time. This is the inverse operation of escapeJava(java.lang.String), but it is not a general unescaping mechanism for Java strings.

      Compared to the `unescapeJava` method in Apache Commons Text StringEscapeUtils, this one correctly handles non-printable ASCII characters.

      Parameters:
      orig - string to quote
      Returns:
      quoted version of orig
    • isBlank

      @Pure public static boolean isBlank(String s)
      Returns true if the string contains only white space codepoints, otherwise false.

      In Java 11, use String.isBlank() instead.

      Parameters:
      s - a string
      Returns:
      true if the string contains only white space codepoints, otherwise false
    • removeWhitespaceAround

      @SideEffectFree public static String removeWhitespaceAround(String arg, String delimiter)
      Remove all whitespace before or after instances of delimiter.
      Parameters:
      arg - string to remove whitespace in
      delimiter - string to remove whitespace abutting
      Returns:
      version of arg, with whitespace abutting delimiter removed
    • removeWhitespaceAfter

      @SideEffectFree public static String removeWhitespaceAfter(String arg, String delimiter)
      Remove all whitespace after instances of delimiter.
      Parameters:
      arg - string to remove whitespace in
      delimiter - a non-empty string to remove whitespace after
      Returns:
      version of arg, with whitespace after delimiter removed
    • removeWhitespaceBefore

      @SideEffectFree public static String removeWhitespaceBefore(String arg, String delimiter)
      Remove all whitespace before instances of delimiter.
      Parameters:
      arg - string to remove whitespace in
      delimiter - a non-empty string to remove whitespace before
      Returns:
      version of arg, with whitespace before delimiter removed
    • lpad

      @SideEffectFree public static String lpad(String s, @org.checkerframework.checker.index.qual.NonNegative int length, char c, boolean truncate)
      Returns a string of the specified length, truncated if necessary (in which case the last 3 non-truncated characters are replaced by "..."), and padded with spaces to the left if necessary.
      Parameters:
      s - string to truncate or pad
      length - goal length
      c - the character to use for padding
      truncate - if false, no truncation is done, only padding
      Returns:
      s truncated or padded to length characters
    • lpad

      @SideEffectFree public static String lpad(String s, @org.checkerframework.checker.index.qual.NonNegative int length, char c)
      Returns a string of the specified length, truncated if necessary (in which case the last 3 non-truncated characters are replaced by "..."), and padded with `c` to the left if necessary.
      Parameters:
      s - string to truncate or pad
      length - goal length
      c - character to use for padding
      Returns:
      s truncated or padded to length characters
    • lpad

      @SideEffectFree public static String lpad(String s, @org.checkerframework.checker.index.qual.NonNegative int length)
      Returns a string of the specified length, truncated if necessary (in which case the last 3 non-truncated characters are replaced by "..."), and padded with spaces to the left if necessary.
      Parameters:
      s - string to truncate or pad
      length - goal length
      Returns:
      s truncated or padded to length characters
    • rpad

      @SideEffectFree public static String rpad(String s, @org.checkerframework.checker.index.qual.NonNegative int length, char c, boolean truncate)
      Returns a string of the specified length, truncated if necessary (in which case the last 3 non-truncated characters are replaced by "..."), and padded with the given character to the right if necessary.
      Parameters:
      s - string to truncate or pad
      length - goal length
      c - character to use for padding
      truncate - if false, no truncation is done, only padding
      Returns:
      s truncated or padded to length characters
    • rpad

      @SideEffectFree public static String rpad(String s, @org.checkerframework.checker.index.qual.NonNegative int length, char c)
      Returns a string of the specified length, truncated if necessary (in which case the last 3 non-truncated characters are replaced by "..."), and padded with the given character to the right if necessary.
      Parameters:
      s - string to truncate or pad
      length - goal length
      c - character to use for padding
      Returns:
      s truncated or padded to length characters
    • rpad

      @SideEffectFree public static String rpad(String s, @org.checkerframework.checker.index.qual.NonNegative int length)
      Returns a string of the specified length, truncated if necessary (in which case the last 3 non-truncated characters are replaced by "..."), and padded with spaces to the right if necessary.
      Parameters:
      s - string to truncate or pad
      length - goal length
      Returns:
      s truncated or padded to length characters
    • rpad

      @SideEffectFree public static String rpad(int num, @org.checkerframework.checker.index.qual.NonNegative int length)
      Converts the int to a String, then formats it using rpad(String,int).
      Parameters:
      num - int whose string representation to truncate or pad
      length - goal length
      Returns:
      a string representation of num padded to length characters
    • rpad

      @SideEffectFree public static String rpad(double num, @org.checkerframework.checker.index.qual.NonNegative int length)
      Converts the double to a String, then formats it using rpad(String,int). Does not do truncation that is after a decimal point.
      Parameters:
      num - double whose string representation to truncate or pad
      length - goal length
      Returns:
      a string representation of num padded to length characters
    • tokens

      @SideEffectFree public static List<Object> tokens(String str, String delim, boolean returnDelims)
      Returns a ArrayList of the Strings returned by StringTokenizer(String,String,boolean) with the given arguments.

      The static type is ArrayList<Object> because StringTokenizer extends Enumeration<Object> instead of Enumeration<String> as it should (probably due to backward-compatibility).

      Parameters:
      str - a string to be parsed
      delim - the delimiters
      returnDelims - flag indicating whether to return the delimiters as tokens
      Returns:
      vector of strings resulting from tokenization
    • tokens

      @SideEffectFree public static List<Object> tokens(String str, String delim)
      Returns a ArrayList of the Strings returned by StringTokenizer(String,String) with the given arguments.
      Parameters:
      str - a string to be parsed
      delim - the delimiters
      Returns:
      vector of strings resulting from tokenization
    • tokens

      @SideEffectFree public static List<Object> tokens(String str)
      Returns a ArrayList of the Strings returned by StringTokenizer(String) with the given arguments.
      Parameters:
      str - a string to be parsed
      Returns:
      vector of strings resulting from tokenization
    • isVersionNumber

      public static boolean isVersionNumber(String text)
      Returns true if the given text is a version number. It has the form N.N or N.N.N, etc., where each N consists of digits.
      Parameters:
      text - a string
      Returns:
      true if the given text is a version number
    • isVersionNumberLE

      public static boolean isVersionNumberLE(String v1, String v2)
      Returns true if the first version number is less than or equal to the second version number.
      Parameters:
      v1 - a version number
      v2 - a version number
      Returns:
      true if the given text is a version number
    • toStringAndClass

      @SideEffectFree public static String toStringAndClass(@Nullable Object v)
      Gives a string representation of the value and its class. Shows elements of collections; to omit them, pass false to toStringAndClass(Object, boolean).
      Parameters:
      v - a value; may be null
      Returns:
      the value's toString and its class
    • toStringAndClass

      @SideEffectFree public static String toStringAndClass(@Nullable Object v, boolean shallow)
      Gives a string representation of the value and its class. Intended for debugging.
      Parameters:
      v - a value; may be null
      shallow - if true, do not show elements of arrays and lists
      Returns:
      the value's toString and its class
    • listToStringAndClass

      @SideEffectFree public static String listToStringAndClass(@Nullable List<? extends @Signed @PolyNull Object> lst)
      Gives a string representation of the value and its class. Intended for debugging.
      Parameters:
      lst - a value; may be null
      Returns:
      the value's toString and its class
    • listToString

      @SideEffectFree public static String listToString(@Nullable List<? extends @Signed @PolyNull Object> lst)
      For use by toStringAndClass. Calls toStringAndClass on each element, but does not add the class of the list itself.
      Parameters:
      lst - the list to print
      Returns:
      a string representation of each element and its class
    • arrayToStringAndClass

      @SideEffectFree public static String arrayToStringAndClass(@Nullable Object a)
      Returns a string representation of the contents of the specified array. The argument must be an array or null. This just dispatches one of the 9 overloaded versions of java.util.Arrays.toString().
      Parameters:
      a - an array
      Returns:
      a string representation of the array
      Throws:
      IllegalArgumentException - if a is not an array
    • mapToStringAndClass

      @Deprecated @SideEffectFree public static String mapToStringAndClass(Map<? extends @Signed @PolyNull Object,? extends @Signed @PolyNull Object> m)
      Convert a map to a string, printing the runtime class of keys and values.
      Parameters:
      m - a map
      Returns:
      a string representation of the map
    • mapToStringLinewise

      @Deprecated @SideEffectFree public static String mapToStringLinewise(Map<? extends @Signed @PolyNull Object,? extends @Signed @PolyNull Object> m)
      Convert a map to a string, printing each key-value pair on its own line, with no indentation.
      Parameters:
      m - a map
      Returns:
      a string representation of the map
    • nplural

      @SideEffectFree public static String nplural(int n, String noun)
      Returns either "n noun" or "n nouns" depending on n. Adds "es" to words ending with "ch", "s", "sh", or "x", adds "ies" to words ending with "y" when the previous letter is a consonant.
      Parameters:
      n - count of nouns
      noun - word being counted; must not be the empty string
      Returns:
      noun, if n==1; otherwise, pluralization of noun
      Throws:
      IllegalArgumentException - if the length of noun is 0
    • conjunction

      @SideEffectFree public static String conjunction(String conjunction, List<? extends @Signed @PolyNull Object> elements)
      Creates a conjunction or disjunction, like "a", "a or b", and "a, b, or c". Obeys the "serial comma" or "Oxford comma" rule: when the list has size 3 or larger, puts a comma after every element but the last.
      Parameters:
      conjunction - the conjunction word, like "and" or "or"
      elements - the elements of the conjunction or disjunction
      Returns:
      a conjunction or disjunction string
    • count

      @Pure @StaticallyExecutable public static int count(String s, int ch)
      Returns the number of times the character appears in the string.
      Parameters:
      s - string to search in
      ch - character to search for
      Returns:
      number of times the character appears in the string
    • count

      @Pure @StaticallyExecutable public static int count(String s, String sub)
      Returns the number of times the second string appears in the first.
      Parameters:
      s - string to search in
      sub - non-empty string to search for
      Returns:
      number of times the substring appears in the string
    • abbreviateNumber

      @SideEffectFree public static String abbreviateNumber(long val)
      Convert a number into an abbreviation such as "5.00K" for 5000 or "65.0M" for 65000000. K stands for 1000, not 1024; M stands for 1000000, not 1048576, etc. There are always exactly 3 decimal digits of precision in the result (counting both sides of the decimal point).
      Parameters:
      val - a numeric value
      Returns:
      an abbreviated string representation of the value
    • countFormatArguments

      @Pure @StaticallyExecutable public static int countFormatArguments(String s)
      Returns the number of arguments that the given format string takes. This is the number of specifiers that take arguments (some, like %n and %%, do not take arguments).
      Parameters:
      s - a string
      Returns:
      the number of format specifiers in the string
    • toStringTruncated

      @SideEffectFree public static String toStringTruncated(Object o, int length)
      If the string representation of the given object is greater than the given length, truncate it to that length.
      Parameters:
      o - an object
      length - the maximum length for the string representation; must be 6 or more
      Returns:
      the string representation of the object, no more than the given length