I'm trying to split a specific String of the format
0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;
in order to extract and save value01
and value02
. How can I do this?
Here is what i tried so far:
//buffer contains a String like: "0001,0004,dd/mm/yy hh:mm:ss,01,18,750"
String string = new String(buffer,0,len);
String[] parts = string.split(",");
String temp = parts[5];
String lum = parts[6];
System.out.print(temp);
System.out.print(lum);
With this code I get ArrayIndexOutofBounds when running the program in Netbeans. Image of error description
Also tried this method:
//buffer contains a String like: "0001,0004,dd/mm/yy hh:mm:ss,01,18,750"
String s= new String(buffer,0,len);
String aux = s + ",";
String[] dados = aux.split(",");
float valor1 = Float.parseFloat(dados[5]);
float valor2 = Float.parseFloat(dados[6]);
System.out.print(aux);
This:
String temp = parts[5];
String lum = parts[6];
Should be this:
String temp = parts[4];
String lum = parts[5];
Remember that arrays in Java are zero-based . So if you do this:
String[] parts = "0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02".split(",");
Then "0001" would be in parts[0]
, "0004" in parts[1]
, "value01" in parts[4]
etc.
Achieving what you're trying to do is acutally pretty easy.
Assuming that your string really always looks like:
0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;
Just cut off the start of the string which you don't need and extract the values afterwards:
// This can be done in hundreds of ways, for the sake of simplicity i'll use substring
String s ="0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;";
String cutOff = s.substring(31, s.length()-1);
String[] results = cutOff.split(",");
please find below code. It has just a bit modification in Andrew's code. Since we are storing the string after splitting into a String array and it's obvious that array index starts with 0. That's why in order to get value01 and value02, we should use index 4 and 5.
public class JavaApplication1
{
public static void main(String[] args)
{
String str="0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02";
String [] strArr=str.split(",");
String temp=strArr[4];
String lum=strArr[5];
System.out.println(temp);
System.out.println(lum);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.