Java String Format formatString(String stringFormat, String... args)

Here you can find the source of formatString(String stringFormat, String... args)

Description

Format string such like "Input params {0} could be {1} "

License

Open Source License

Parameter

Parameter Description
stringFormat a parameter
args a parameter

Declaration

public static String formatString(String stringFormat, String... args) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*  w w  w  . j a  v a 2s.  c  o m*/
     * Format string such like "Input params {0} could be {1} "
     * @param stringFormat
     * @param args
     * @return
     */
    public static String formatString(String stringFormat, String... args) {
        if (args.length == 0) {
            return stringFormat;
        } else {
            List<String> listArgs = new ArrayList<String>();

            for (String arg : args) {
                listArgs.add(arg);
            }

            StringBuilder sb = new StringBuilder(stringFormat);
            int beginIndex = 0;
            int endIndex = 0;
            int argIndex = 0;

            for (int index = 0; index < sb.length();) {
                beginIndex = sb.indexOf("{", index);
                if (beginIndex < 0) {
                    break;
                }
                endIndex = sb.indexOf("}", beginIndex);
                if (endIndex < 0) {
                    break;
                }

                argIndex = Integer.parseInt(sb.substring(beginIndex + 1, endIndex));

                sb.replace(beginIndex, endIndex + 1, listArgs.get(argIndex));

                index = beginIndex + listArgs.get(argIndex).length();
            }

            return sb.toString();
        }
    }
}

Related

  1. formatMailtoLink(String emailAddress)
  2. formatMessage(String message)
  3. formatNameToMimeType(final String formatName)
  4. formatParam(String param)
  5. formatProtein(String seq)
  6. formatStringTo80Columns(String str)
  7. formatTooltip(String tooltip)
  8. formatTreeLines(String tree)
  9. formatVarname(StringBuilder buffer, Object varname)