Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to remove trailing tab in a string in java

If you have for example a list of tab-separated values:

foo1\tfoo2\tfoo3\tfoo4\t

The last \t was added due to automatic appending of the \t with each +=.

How do you remove that last \t in a easy way? So that the result is:

foo1\tfoo2\tfoo3\tfoo4

As a request from Hover, a small example of what I had:

String foo = "";
for (int i = 1; i <= 100; i++) {
    foo += "foo" + "\t";
    if (i % 10 == 0) {
        foo = foo.trim(); // wasn't working
        foo += "\n";
    }
}
System.out.println(foo);

Output (replaced actual tab with stringed tab for display here):

foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t

That's the main reason I asked this question, .trim() wasn't working, therefore, I tough that trim() wasn't made for trailing tabs.

like image 460
link_boy Avatar asked Feb 06 '13 04:02

link_boy


1 Answers

String s1 = "foo1\tfoo2\tfoo3\tfoo4\t".trim();
like image 167
Ren Avatar answered Nov 07 '22 15:11

Ren