将循环结果另存为字符串

时间:2013-09-17 14:17:01

标签: java arrays string

    String input[] = request.getParameterValues("checkbox");

        for(int i=0;i<input.length;i++) {
            if (i==input.length-1) {
                System.out.print(input[i]+" ");
            } else {
                    System.out.print(input[i]+", ");
            }
        }

结果是我打印到控制台,如“CustomerId,FirstName,LastName,Phone”。 我想将for循环的结果保存为字符串变量,所以我可以做

     String query = "select "+result above+" from table";

怎么做?

3 个答案:

答案 0 :(得分:3)

您继续追加到StringBuilder,然后将其转换为String

StringBuilder sb = new StringBuilder();
for(int i=0;i<input.length;i++) {
  if (i==input.length-1) {
     System.out.print(input[i]+" ");
     sb = sb.concat(input[i] + ",");
  } else {
     System.out.print(input[i]+", ");
     sb = sb.concat(input[i] + ",");
  }
}

然后,

String query = "select "+sb.toString()+" from table";

答案 1 :(得分:2)

使用StringBuilder将字符串连接在一起。 (技术上可以使用String对象,并使用+运算符将它们连接在一起,但这有很多缺点......)

    String input[] = request.getParameterValues("checkbox");

    StringBuilder sb = new StringBuilder(); // create empty StringBuilder instance
    for(int i=0;i<input.length;i++) {
        sb.append(input[i]);     //append element
        if (i==input.length-1) {
            sb.append(" ");      //append space
        } else {
            sb.append(", ");     //append comma
        }
    }

    String result = sb.toString();
    Systemout.println(result);

或者你可以使用StringBuilder对象构建(see Builder pattern)整个查询,每个部分的方法(addFields(StringBuilder sb)addFromPart(StringBuilder sb)addWhereClause(StringBuilder sb))和瞧,你有一个小型数据访问框架的内部......

public abstract class MyQueryBuilder {

    protected abstract void addFields(StringBuilder sb);
    protected abstract void addFromPart(StringBuilder sb);
    protected abstract void addWhereClause(StringBuilder sb);

    public final String getQuery() {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT ");

        addFields(sb); //this adds the fields to be selected
        sb.append(" FROM ");

        addFromPart(sb); //this adds the tables in the FROM clause

        addWhereClause(sb); //this adds the where clause
        //...etc
        return sb.toString();
    }
}

答案 2 :(得分:1)

您可以使用StringBuilder执行此操作,而不是将值打印出来。

String input[] = request.getParameterValues("checkbox");

    StringBuilder builder = new StringBuilder();

    for(int i=0;i<input.length;i++) {
        if (i==input.length-1) {
            builder.append(input[i]+" ");
        } else {
                builder.append(input[i]+", ");
        }
    }

此致 kayz