[英]Splitting a String built from a char array
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
.为了提取和保存
value01
和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.使用此代码,我在 Netbeans 中运行程序时得到 ArrayIndexOutofBounds。 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 .请记住, Java 中的数组是从零开始的。 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.然后“0001”将在
parts[0]
,“0004”在parts[1]
,“value01”在parts[4]
等中。
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.
它只是对 Andrew 的代码进行了一些修改。 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.
由于我们将字符串拆分成String数组后存储,很明显数组索引是从0开始的,所以为了得到value01和value02,我们应该使用索引4和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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.