In my program I need to convert char[]
of fixed size into trimmed String (without blank spaces taken from an array). At the moment I do new String(array).trim()
but I would like to avoid trim()
if possible. Any advice how to do it better?
Best Regards.
Asked
Active
Viewed 175 times
5

Farvardin
- 5,336
- 5
- 33
- 54

Enzomatric
- 487
- 8
- 19
-
1give a sample char[] with elements in it – Rod_Algonquin Aug 20 '14 at 08:04
-
2So you want to get rid of the spaces at the start and end? Trim does so. What you say with "spaces taken from an array" is not achievable using trim. – Seyf Aug 20 '14 at 08:08
-
The example char is [1,2,3, , , , , ,], the resulting String should be 123 (no spaces left). – Enzomatric Aug 20 '14 at 08:36
2 Answers
7
but I would like to avoid trim() if possible. Any advice how to do it better?
Do not look for any alternative and trim()
is smart enough which uses substring()
method internally. That is fast enough.
Any looping or reg-ex based solutions will hit you hard.

Suresh Atta
- 120,458
- 37
- 198
- 307
3
If you use trim source code and rewrite it a little bit, you can remove unused (in your case) substring method:
trim source code:
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
Test:
public static char[] value = new char[]{' ', ' ', 't', 'w', 's', ' ', ' ', ' '};
public static void main(String[] args) {
normal();
optimized();
}
public static void normal() {
long start = System.nanoTime();
String s = new String(value).trim();
System.out.println("normal : '" + s + "' " + (System.nanoTime() - start) + "ns");
}
public static void optimized() {
long start = System.nanoTime();
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
String s = new String(value, st, len - st);
System.out.println("optimized: '" + s + "' " + (System.nanoTime() - start) + "ns");
}
The output:
run:
normal : 'tws' 41656ns
optimized: 'tws' 7546ns
So, your version of new trimmed string will save you some time.

Alexey Odintsov
- 1,705
- 11
- 13
-
2These times mean absolutely nothing. You should use jmh if you want to microbenchmark the two possibilities. – Svetlin Zarev Aug 20 '14 at 08:32
-
1@Svetlin Zarev 1# - I provided source code of trim function from JDK. 2# But it is obvious that we removed unused susbtring call. – Alexey Odintsov Aug 20 '14 at 08:41