Reputation: 1047
I have String[] array that contains a string with three data points separated by the character ":" like the following string:
SNSD_OOT:511:127
I need to extract this values from the String[] array. I tried using statusOxymetry[i] = Arrays.toString(valuesOxymetry[i].split(":")); However I end up with the following data. I need to store each element into an array.
[SNSD_OOT, 511, 127]
My goal is to end with 3 arrays, one where anything before the first ":" appears, another one for the data after the first ":", and the final one for the data after the second ":"
1stArray[0] = SNSD
2ndArray[0] = 511
3rdArray[0] = 127
I need to separate the first, second, and third element into a separate array each. I am feeling a bit confused on how to do this properly.
String[] valuesOxymetry = message.getData().getString("raw"));
int total = valuesOxymetry.length - 2;
String[] statusOxymetry = new String[total];
String[] hrmOxymetry = new String[total];
String[] spo2Oxymetry = new String[total];
//ignore first two data points (timestamp)
for(int i = 2; i < total; i++) {
System.out.println("Pulse values: " + valuesOxymetry[i]);
statusOxymetry[i] = Arrays.toString(valuesOxymetry[i].split(":"));
System.out.println("Only status " + statusOxymetry[i]);
}
Upvotes: 0
Views: 782
Reputation: 3225
You can do this:
public static void main(String[] ar) throws Exception{
String dataraw = "SNSD_OOT:511:127";
//take every array from result list
//print first element
toListStringArray(dataraw)
.forEach(
e -> System.out.println(e[0])
);
}
public static List<String[]> toListStringArray(String dataraw){
//split string
String[] dataArray = dataraw.split(":");
//list which contains all arrays
List<String[]> result = new ArrayList<>();
//take every element from split
//put into an array which will contains only that element
//put array in list
for(String e : dataArray){
result.add(new String[]{e});
}
return result;
}
I don't see why to do this. I also recommend to look at @Joni answer
Upvotes: 1
Reputation: 19555
It should be:
for(int i = 2, j = 0; i < total; i++, j++) {
System.out.println("Pulse values: " + valuesOxymetry[i]);
String[] values = valuesOxymetry[i].split(":");
statusOxymetry[j] = values[0];
hrmOxymetry [j] = values[1];
spo2Oxymetry [j] = values[2];
}
Upvotes: 2
Reputation: 111289
The String.split
method returns an array. Store that array in a new variable, and use that new variable:
String[] splitValues = valuesOxymetry[i].split(":")
statusOxymetry[i] = splitValues[0]; // SNSD_OOT
hrmOxymetry[i] = splitValues[1]; // 511
spo2Oxymetry[i] = splitValues[2]; // 127
That said, there may be a cleaner way to do this. For example you could create a class that represents data records as independent entities, instead of striping the data across "parallel arrays."
Upvotes: 3