如何在Java中删除最后一个字符字符串

3

我想去掉最后一个数据中的逗号。

示例:

我有以下代码:

StringBuilder temp = new StringBuilder();

for (int i=0; i<allLines.size(); i++){
     StringBuilder temp2 = new StringBuilder();

     String[] abc = line.split("\t");

     temp2.append("{");
     temp2.append("id: \""+abc[0]+"\",");
     temp2.append("name: \""+abc[1]+"\",");
     temp2.append("},");

     temp.append(temp2.toString()); 

}

System.out.println("result : "+temp.toString());

ihave code and result:

{id: "1", name: "Jhames"},{id: "2", name: "Richard"},

但我想要结果:
{id: "1", name: "Jhames"},{id: "2", name: "Richard"}

为什么要创建另一个 StringBuilder 并将其附加到第一个 StringBuilder 中? - khelwood
正如我在下面的回答中所说,你只需要在代码中添加一行 temp.setLength(sb.length() - 1); 就可以使其工作,但我同意你应该像 khelwood 提到的那样只使用一个 StringBuilder。 - Tuxxy_Thang
抱歉,我的原始代码中有一个打字错误,应该是temp.setLength(temp.length() - 1);。 - Tuxxy_Thang
不要使用stringBuilder.append("foo" + x),因为由于串联,此代码与stringBuilder.append(new StringBuilder("foo).append(x).toString())相同,因此可以看出它有点否定了拥有stringBuilder的目的。相反,请使用stringBuilder.append("foo").append(x) - Pshemo
6个回答

8

只需使用新的Java 8 StringJoiner!(以及其他巧妙的Java方法)

示例:

StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"

它还支持以形式的流 Collectors.joining(",")

完整示例:

public static void main(String[] args) {

    String input = "1\tJames\n2\tRichard";
    String output =  Arrays.stream(input.split("\n"))
                        .map( i -> String.format("{ id: \"%s\", name: \"%s\" }", i.split("\t")))
                        .collect(Collectors.joining(","));

    //prints: { id: "1", name: "James" },{ id: "2", name: "Richard" }       
    System.out.println(output);

}

4
您可以避免一开始就添加它:
for (int i=0; i<allLines.size(); i++){
     StringBuilder temp2 = new StringBuilder();

     String[] abc = line.split("\t");

     temp2.append("{");
     temp2.append("id: \""+abc[0]+"\",");
     temp2.append("name: \""+abc[1]+"\",");
     temp2.append("}");
     if (i<allLines.size()-1)
         temp2.append(",");
     temp.append(temp2.toString()); 

}

3

或者在for循环之后添加以下内容

    temp.setLength(temp.length() - 1);

这需要您的代码中不需要进行常量索引检查


2
您可以使用deleteCharAt()方法。
 StringBuilder s = new StringBuilder("{id: \"1\", name: \"Jhames\"},{id: \"2\", name: \"Richard\"},");
 System.out.println(s.deleteCharAt(s.lastIndexOf(",")));

2
首先,您不需要使用两个StringBuilder,因此可以用下面的方式代替:
StringBuilder sb1 = ..
for(..){
    StringBuilder sb2 = ...
    //fill sb2
    sb1.append(sb2);
}

你应该使用:
StringBuilder sb1 = ..
for(..){
    //add all you want to sb1
    sb1.append(..)
    sb1.append(..)
}

下一件事是你绝不想做的。
sb.appent("foo" + x + "bar");

因为它与

相同。

sb.append(new StringBuilder("foo").append(x).append("bar").toString())

这种方法非常低效,因为:

  1. 每次这样做时都会创建一个单独的StringBuilder
  2. 这个新的StringBuilder需要不必要地调用toString方法,它必须复制所有字符到新字符串中,然后再复制到构建器中,而不是调用append(StringBuilder)并直接复制其字符。

因此,始终使用sb.appent("foo" + x + "bar");的方法来代替。

sb.appent("foo").append(x).append("bar");

现在让我们回到您的主要问题。由于您的代码没有声明line变量,我假设
String[] abc = line.split("\t");

你的意思是什么?
String[] abc = allLines.get(i).split("\t");

所以您的代码可以如下所示:
StringBuilder temp = new StringBuilder();

for (int i = 0; i < allLines.size(); i++) {

    String[] abc = allLines.get(i).split("\t");

    temp.append("{id: \"").append(abc[0]).append("\", ");
    temp.append("name: \"").append(abc[1]).append("\"}");
    if (i < allLines.size() - 1)
        temp.append(", ");
}

System.out.println("result : " + temp.toString());

1

没有Java 8的解决方案:

StringBuilder temp = new StringBuilder();
adder(temp, allLines.get(0));

for (int i=1; i<allLines.size(); i++){
     temp.append(",");
     adder(temp, allLines.get(i));
}
System.out.println("result : "+temp.toString());

private static void adder(StringBuilder temp,String line){
    String[] abc = line.split("\t");
    temp.append("{id: \"");
    temp.append(abc[0]);
    temp.append("\",");
    temp.append("name: \"");
    temp.append(abc[1]);
    temp.append("\"}");
}

请正确使用append(不要在内部进行字符串连接) - Rob Audenaerde

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接