Remove empty string elements from array of strings in Java
I am trying to get the contents of a text file, delete everything except alphabets, and then convert it to an array String
to process words individually. I do this to get a text file:
String temp1= IOUtils.toString(FIS,"UTF-8");
String temp2=temp1.replaceAll("[,.!;:\\r\\n]"," ");
And then, to tokenize the string, I do this:
String[] tempStringArray = temp2.split(" ");
The problem is that when the array is created, there are empty ones String
for different indices. These String
blanks are at the linebreak position, more than one space, replace punctuation marks, etc. in a text file.
I want these blanks to String
be removed from my array String
or in such a way that they cannot enter the array String
.
How can I do that?
source to share
In your example, if you have more than one character from the character set [,.!;: \ R \ n] in a string, it will replace it with multiple whitespace. When you call the method split()
, it then puts empty entries into the array that refer to multiple spaces in the string.
You can use regex in the method split()
, which will work much better for your example.
Try replacing temp2.split(" ")
with temp2.split("\\s+")
. This will search for multiple whitespace in the string and simply symbolize text around large whitespace whitespace.
source to share