Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim strings in java without creating a new object?

Tags:

java

string

trim

I have a large text file(about 20 million lines) which has lines in the following format :

<string1>, <string2>

Now those strings may have trailing or leading whitespaces which I want to remove on reading the file.

I am currently using trim() for this purpose but since String in Java is immutable, trim() is creating a new object per trim operation. This is leading to too much wastage of memory.

How can I do it better?

like image 298
Abhishek Kaushik Avatar asked Feb 25 '26 22:02

Abhishek Kaushik


1 Answers

I would be surprised if the immutable String class is causing problems; the JVM is very efficient and the result of many years of engineering work.

That said, Java does provide a mutable class for manipulating strings called StringBuilder. You can read the docs here.

If you are working across threads, consider using StringBuffer.

like image 117
sdgfsdh Avatar answered Feb 27 '26 10:02

sdgfsdh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!