3

I want to remove comma in last data.

example:

i have code:

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"},

but i want result:

{id: "1", name: "Jhames"},{id: "2", name: "Richard"}
4
  • Why are you creating another stringbuilder and appending it to your first stringbuilder? Commented Jun 22, 2015 at 8:22
  • as I said in my answer below, you just have to add 1 line to your code to get this to work temp.setLength(sb.length() - 1); but I agree you should just use the one StringBuilder as mentioned by khelwood Commented Jun 22, 2015 at 8:33
  • sorry had a typo in my original code should have been temp.setLength(temp.length() - 1); Commented Jun 22, 2015 at 8:40
  • Don't ever use stringBuilder.append("foo" + x) since because of concatenation this code is same as stringBuilder.append(new StringBuilder("foo).append(x).toString()), so as you see it kind of negates purpose of having stringBuilder. Instead use stringBuilder.append("foo").append(x). Commented Jun 22, 2015 at 9:22

6 Answers 6

8

Just use the new java 8 StringJoiner! (And other nifty Java methods)

Example:

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

It also supports streams in the form of Collectors.joining(",")

Full example:

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);

}
Sign up to request clarification or add additional context in comments.

Comments

4

You can avoid appending it in the first place :

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()); 

}

Comments

3

Alternatively add this after your for loop

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

which requires no constant index checking in your code

Comments

2

You can use deleteCharAt() method.

 StringBuilder s = new StringBuilder("{id: \"1\", name: \"Jhames\"},{id: \"2\", name: \"Richard\"},");
 System.out.println(s.deleteCharAt(s.lastIndexOf(",")));

Comments

2

First of all you don't need two StringBuilders, so instead of

StringBuilder sb1 = ..
for(..){
    StringBuilder sb2 = ...
    //fill sb2
    sb1.append(sb2);
}

you should use

StringBuilder sb1 = ..
for(..){
    //add all you want to sb1
    sb1.append(..)
    sb1.append(..)
}

Next thing is that you don't ever want to do

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

because it is same as

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

which is very ineffective because:

  1. you are creating separate StringBuilder each time you do so
  2. this new StringBuilder needs to unnecessary call toString method which has to copy all characters to new String which will later be copied to builder, instead of calling append(StringBuilder) and copy its characters directly.

So instead of sb.appent("foo" + x + "bar"); always write

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

Now lets go back to your main problem. Since your code doesn't have declaration of line variable I am assuming that by

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

you mean

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

So your code can look like

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());

Comments

1

No Java 8 solution:

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("\"}");
}

1 Comment

Please use append properly (don't do String concatenation inside)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.