Search code examples
javastringstringbuilder

How to remove the last string from a stringbuilder?


I'm dynamically creating a string

StringBuilder preparedStatement = new StringBuilder();
states.keySet().forEach(key -> preparedStatement
               .append(key)
               .append(" = ")
               .append(":")
               .append(key)
               .append(" AND "));

I want to remove the last AND at the end of the loop. Is this possible?


Solution

  • Yes. You know how wide the " AND " is, so just use StringBuilder#delete:

    preparedStatement.delete(preparedStatement.length() - " AND ".length(),
                             preparedStatement.length()
                            );
    

    Or, if you're about to turn it into a String anyway, use StringBuilder#substring:

    String result = preparedStatement.substring(0,
                                                preparedStatement.length()
                                                    - " AND ".length()
                                               );