我正在研究android项目。我从加速度计和陀螺仪传感器获得传感器值,例如A1 A2 A3 G1 G2 G3。考虑字符串模式" -553 39 -415 -540 168 -209"。那么如何从这个字符串模式中提取-553,39,-415值并分配给变量A1,A2,A3并类似地提取-540,168 , - 209并分配给G1,G2,G3。我已将其转换为ArrayList但是当从中读取值时,应用程序崩溃。任何其他想法得到结果?
使用ArrayList:
String str= "-553 39 -415 -540 168 -209";
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(str));
String x1 = myList.get(0);
String y1 = myList.get(1);
String z1 = myList.get(2);
String x2 = myList.get(3);
String y2 = myList.get(4);
String z2 = myList.get(5);
Log.d("Accel",x1 );
Log.d("Accel",y1 );
Log.d("Accel",z1 );
Log.d("Gyro",x2 );
Log.d("Gyro",y2 );
Log.d("Gyro",z2 );
答案 0 :(得分:0)
使用str.split("\\s")
拆分字符串。
String str = "-553 39 -415 -540 168 -209";
List<String> myList = Arrays.asList(str.split("\\s"));
String x1 = myList.get(0);
String y1 = myList.get(1);
String z1 = myList.get(2);
String x2 = myList.get(3);
String y2 = myList.get(4);
String z2 = myList.get(5);
Log.d("Accel",x1 );
Log.d("Accel",y1 );
Log.d("Accel",z1 );
Log.d("Gyro",x2 );
Log.d("Gyro",y2 );
Log.d("Gyro",z2 );