Reputation: 74
I need to remove a line from string if some column is empty: Check it:
ArrayList<String> students = new ArrayList<>();
students.add("8246, ,JUCIELLY,SOUSA,ENSINO REGULAR - MEDIO - 1ช SERIE,[email protected],10071999");
students.add("8246,1282,JUCIELLY,SOUSA,ENSINO REGULAR - MEDIO - 1ช SERIE,[email protected],10071999");
students.add("8246,1282,JUCIELLY,SOUSA,ENSINO REGULAR - MEDIO - 1ช SERIE,[email protected],10071999");
students.add("8246,,JUCIELLY,SOUSA,ENSINO REGULAR - MEDIO - 1ช SERIE,[email protected],10071999");
students.add("8246,1282,,[email protected],10071999");
students.add("8246,1282, ,,10071999");
As you can see some colunms on this strins is EMPTY or " "(have blankspaces)
someone can help me? i think it is easy to do but i tried and failed.
i need a full 7 columns with something. cannot be ,, or blankspaces =\
Upvotes: 0
Views: 50
Reputation: 8008
check for empty values and keep track of the indices. later remove elements from those indices
ArrayList<Integer> badIndices = new ArrayList<Integer>();
for (int i=0; i<students.size ; i++)
{
if (students.get(i).matches(".*,\\s?,.*")) {
badIndices.add(i);
}
}
for (int b : badIndices)
{
student.remove(b);
}
now, all of the bad entries would have been removed.
Upvotes: 1
Reputation: 7880
You can also use contains
method of String class:
if(element.contains(",,")||element.contains(", ,")){
//do something
}
Upvotes: 0
Reputation: 2037
When you are parsing a string in Java
you can use the String.split(identifier)
function, which will split a String
on the character you give the function, and return an Array
of all things in between the character you are splitting on. What you are trying to do is parse a csv (comma separated value) record. So as the naming would suggest, use a "," as your separator.
The below example will split the String
(a student record) based on the comma value, and then loop through each of the values that are between the commas. It will then call String.trim()
, which will remove any leading/trailing whitespace from the String
value, and then check if String.isEmpty()
returns true
. If it does, we know that this is an object that should be removed from the list.
String student = "8246, ,JUCIELLY,SOUSA,ENSINO REGULAR - MEDIO - 1ช SERIE,[email protected],10071999";
String [] studentStringSplit = student.split(",");
for(String fieldValue : studentStringSplit){
if(fieldValue.trim().isEmpty()){
//remove record from list
}
}
It is worth noted that Java
is an Object-Oriented programming language, so instead of passing 1 large String
into a List
, you should instead create a new Class
to represent these person records with, and then create/use a List
of each person. But, that would not necessarily change the procedure for finding empty values at all. Just side advice!
Upvotes: 0
Reputation: 13222
Split the String
and see if any indexes are empty or equal to " "
...
String.split(",");
Upvotes: 1