如何在java中的stringBuilder对象的两侧附加单引号

时间:2015-05-26 17:40:31

标签: java string append stringbuilder

我想将单引号添加到字符串数组中。如果我有5个值。(1,2,3,4,5)。我需要这样的' 1'' 2'' 3',' 4'' 5'

我尝过以下一些但是我收到了错误

public class Main()
{
        StringBuilder values=new StringBuilder();           

            values=getValues(1);

            System.out.println(values.toString());

            public StringBuilder getValues(int productid){
                    StringBuilder Variable_1=new StringBuilder();       
                    Variable_1=get(productid);                  
                    return Variable_1.deleteCharAt(Variable_1.length()-1);
                }

    public static StringBuilder get(String product)
    {
    /Some quoatoes to retrive value from db/
    while (rs.next()) {
                    number = rs.getString("org");
                    orgNames.append("'");
                    orgNames.append(number);
                    orgNames.append("'");
                    orgNames.append(",");

                }
    return orgNames;
    }
}  

我的例外情况如下

  java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:766)
        at java.lang.StringBuilder.deleteCharAt(StringBuilder.java:280)
        at calc.getValues(process.java:8)

4 个答案:

答案 0 :(得分:1)

我不太确定你的代码是做什么的,但是我已经编写了一个函数,它将Strings数组作为输入并用引号括住每个元素。

String[] appendQuotes(String[] array)
{
    List<String> result = new ArrayList<>();
    for(String str : array)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("'");
        sb.append(str);
        sb.append("'");
        result.add(sb.toString());
    }
    return result.toArray();
}

答案 1 :(得分:1)

在最后一次迭代中Variable_1.length() - 1返回索引超出范围,因为 Variable_1.length()为零。

检查

if(Variable_1.length()>0)
在deleteCharAt之前

答案 2 :(得分:0)

Apache Commons Lang 3中已经存在StringUtils.wrap方法,它将char / string附加到其他字符串,使用Java8功能的示例代码如下所示:

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.api.Assertions;
import org.testng.annotations.*;

import java.util.stream.Stream;

public class StringArrayWrapTest {

    public static final String SINGLE_QUOTE_SIGN = "'";

    @Test
    public void stringArrayWrapTest() {
        //given
        String[] arrayOfStrings = {"1", "2", "3", "4", "5"};

        //when
        String[] arrayOfStringsWithQuotes = (String[]) Stream.of(arrayOfStrings)
                .map((stringFromArray -> StringUtils.wrap(stringFromArray, SINGLE_QUOTE_SIGN)))
                .toArray(size -> new String[size]);
        //then
        Assertions.assertThat(arrayOfStringsWithQuotes)
                .containsExactly(new String[]{"'1'", "'2'", "'3'", "'4'", "'5'"});
    }
}

答案 3 :(得分:0)

同样的事情可以通过Spring Framework完成:

import org.springframework.util.StringUtils;

String wrapWithSingleQuotes(String sampleString) {
        return StringUtils.quote(sampleString);
    }