Class StringFormatter

java.lang.Object
ca.corbett.extras.StringFormatter

public class StringFormatter extends Object
A utility class for taking a formatString and performing a configurable mapping using a provided mapper function.

USAGE: Your format string can include any number of tags starting with a percent sign (%) followed by a single character. The ReplaceMapper that you supply will be called with each character that follows a percent sign, and should return the string to replace the tag with. If the mapper returns null, the tag will be left in place as-is. To include a literal percent sign in the output, use %% in the format string.

Examples:

     // This returns: "Hello, Alice! Today is Monday."
     StringFormatter.format("Hello, %n! Today is %d.", ch -> {
         switch (ch) {
             case 'n': return "Alice";
             case 'd': return "Monday";
             default: return null;
         }
     });

     // This returns: "Processing: [step 1 of 3] 50% complete"
     StringFormatter.format("Processing: [step %s of %t] %p%% complete", ch -> {
         switch (ch) {
             case 's': return "1";
             case 't': return "3";
             case 'p': return "50";
             default: return null;
         }
     });
 
Author:
scorbo2
  • Constructor Details

    • StringFormatter

      public StringFormatter()
  • Method Details

    • format

      public static String format(String formatString, StringFormatter.ReplaceMapper mapper)
      Using the given format string and mapper, produce a formatted string.
      Parameters:
      formatString - A format string containing zero or more format tags to be replaced.
      mapper - A mapper which maps format tag characters to their replacement strings.
      Returns:
      The formatted string with all applicable tags replaced.