select {0} from {1} where 1=1如何格式化他 用那个方法就是输出结果为 select  item  from table where 1=1

解决方案 »

  1.   


    public class Test{
    public static void main(String [] args){
    String [] str={"item","table"};
    String sql="select {0} from {1} where 1=1";
    for(int i=0;i<str.length;i++){
    sql=sql.replace("{"+i+"}", str[i]);
    }
           System.out.print(sql);
    }
    }
      

  2.   

    public static final String PLACEHOLDER_PREFIX = "${";/** Suffix for system property placeholders: "}" */
    public static final String PLACEHOLDER_SUFFIX = "}";public static String resolvePlaceholders(String text)
        {
    StringBuffer buf = new StringBuffer(text); int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);
    while (startIndex != -1)
    {
        int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex
        + PLACEHOLDER_PREFIX.length());
        if (endIndex != -1)
        {
    String placeholder = buf.substring(startIndex
    + PLACEHOLDER_PREFIX.length(), endIndex);
    int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
    try
    {
        String propVal = System.getProperty(placeholder);
        if (propVal == null)
        {
    // Fall back to searching the system environment.
    propVal = System.getenv(placeholder);
        }
        if (propVal != null)
        {
    buf.replace(startIndex, endIndex
    + PLACEHOLDER_SUFFIX.length(), propVal);
    nextIndex = startIndex + propVal.length();
        } else
        {
    System.err
    .println("Could not resolve placeholder '"
    + placeholder
    + "' in ["
    + text
    + "] as system property: neither system property nor environment variable found");
        }
    } catch (Throwable ex)
    {
        System.err.println("Could not resolve placeholder '"
        + placeholder + "' in [" + text
        + "] as system property: " + ex);
    }
    startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);
        } else
        {
    startIndex = -1;
        }
    } return buf.toString();
        }
    这是spring处理{}的方法。
      

  3.   


    //看着楼上那些人真辛苦啊,其实 jdk 1.5里面就有 格式化 字符串的 
    String str = "select {0} from {1} where 1=1";
    String c = String.format(str,"item","table");
    //c 就等于 select  item  from table where 1=1
    //就是输出结果为 select  item  from table where 1=1
      

  4.   

    如果只是要替换 何不试试占位符呢?
    String str=String.format("select %s from %s where 1=1", "item","table");
      

  5.   

    String str = "select {0} from {1} where 1=1";
    Object[] a ={"item","table"};
    String str = java.text.MessageFormat.format(str, a);
      

  6.   


    这是 jdk1.5的新特性列,大哥, 你去自己试一下把,我用了 N 次了, 对你我无语
      

  7.   


    不能这么用吧,使用 {0} {1} 占位符只能用 MessageFormat,String.format 或者说是 Formatter 的占位符有特定格式的。要把 {0} {1} 全部改成 %s 才能使用 String.format