Reputation: 109
All the split command I have seen split (for example) a CSV
file into the 1 array.
e.g.
cat,feline,house
dog,canine,house
monkey,primate,zoo
Into
array[0] = cat
array[1] = feline
array[2] = house
Is there a way to split them into separate arrays per line so it would be more like (so you can keep specific attributes in the same lines of the csv
:
into
animal[0] = cat
species[0] = feline
lives[0] = house
Upvotes: 0
Views: 109
Reputation: 26187
Such an abstract split does not exist as a default as far as I know.
The basic way you would go about achieving this, would be first to do the regular split as you said, which gave the result.
array[0] = cat
array[1] = feline
array[2] = house
Then you could loop through the array
and check for the different things.
ArrayList<String> animals = new ArrayList<String>();
ArrayList<String> lives = new ArrayList<String>();
for (int i = 0; i < array.length; i++) {
if (array[i].equalsIgnoreCase("cat") || array[i].equalsIgnoreCase("dog")) {
animals.add(array[i]);
}
else if (array[i].equalsIgnoreCase("house") || array[i].equalsIgnoreCase("zoo")) {
lives.add(array[i]);
}
}
Then you would of course do that for all the cases you have. It's a pretty complex way to do it, though really simple to understand.
To achive what you asked in the comments, you could do something like this.
ArrayList<String> animals = new ArrayList<String>();
ArrayList<String> lives = new ArrayList<String>();
for (int i = 0; i < array.length; i += 5) {
animals.add(array[i]);
lives.add(array[i + 1]);
}
Then the + 1
for selecting the index in the array would of course depend on the index from the splitted String
.
Upvotes: 1
Reputation: 1
String.split
works like separating items by the delimiters, it doesn't know what a item is. If you want to associate items on some pattern to be recognized when parsing the string, you should supply those patterns to the categories the items should be associated to. If it's a CSV and you want to get the table data, then you should supply the metadata described the column names and dimensions. Without this metadata it's impossible to parse your document correctly.
Upvotes: 0
Reputation: 35557
You can try this
BufferedReader br = new BufferedReader(new FileReader("D:\\sample.txt"));
String st = null;
String[] animal = new String[10];
String[] species = new String[10];
String[] lives = new String[10];
int j = 0;
while ((st = br.readLine()) != null) {
String[] str = st.split(",");
for (int i = 0; i < str.length; i++) {
animal[j] = str[0];
species[j] = str[1];
lives[j] = str[2];
}
j++;
}
But it is better to use ArrayList
here.
Upvotes: 1
Reputation: 19284
A much better approach is to create a POJO:
public class MyAnimal {
private String animal;
private String family;
private String place;
private String country;
// getters and setters...
}
Then you can use a parser or read the file line by line and convert it to a List<MyAnimal>
Using array to hold object data is not the way to do it.
Upvotes: 3