String Formatter in GWT

前端 未结 12 831
生来不讨喜
生来不讨喜 2021-02-03 18:59

How do I format my string in GWT?

I made a method

  Formatter format = new Formatter();
    int matches = 0;
    Formatter formattedString = format.forma         


        
12条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-03 19:37

    This one is pretty fast and ignores bad curly-delimited values:

    public static String format(final String format, final Object... args)
    {
        if (format == null || format.isEmpty()) return "";
    
        // Approximate the result length: format string + 16 character args
        StringBuilder sb = new StringBuilder(format.length() + (args.length*16));
    
        final char openDelim = '{';
        final char closeDelim = '}';
    
        int cur = 0;
        int len = format.length();
        int open;
        int close;
    
        while (cur < len)
        {
            switch (open = format.indexOf(openDelim, cur))
            {
                case -1:
                    return sb.append(format.substring(cur, len)).toString();
    
                default:
                    sb.append(format.substring(cur, open));
                    switch (close = format.indexOf(closeDelim, open))
                    {
                        case -1:
                            return sb.append(format.substring(open)).toString();
    
                        default:
                            String nStr = format.substring(open + 1, close);
                            try
                            {
                                // Append the corresponding argument value
                                sb.append(args[Integer.parseInt(nStr)]);
                            }
                            catch (Exception e)
                            {
                                // Append the curlies and the original delimited value
                                sb.append(openDelim).append(nStr).append(closeDelim);
                            }
                            cur = close + 1;
                    }
            }
        }
    
        return sb.toString();
    }
    

提交回复
热议问题