Java字符串拆分错误

时间:2012-01-19 15:15:08

标签: java android string split

我需要拆分字符串数组,然后将其保存为较小的字符串。 Plz帮助我......我做错了什么......

 for(int i=0; i<suburl.size(); i++){

       String temp = suburl.get(i);
   String[] data = temp.split(" ");

   Log.i("DATA 0", data[0]);
   Log.i("DATA 1", data[1]);
   Log.i("DATA 2", data[2]);
 }

这里

 public static ArrayList<String> suburl = new ArrayList<String>();

其中,

   suburl.get(0) = "alex 21 engineer"
   suburl.get(1) = "mike 22 lawyer"
   suburl.get(2) = "sunny 26 deisnger"
   suburl.get(3) = "kim 24 painter"

   String[] data;

但是分裂时我得到的错误是.......

  01-19 20:35:09.820: E/AndroidRuntime(1672): Caused by:    java.lang.ArrayIndexOutOfBoundsException
  01-19 20:35:09.820: E/AndroidRuntime(1672):   at  flash.com.MainActivity.onCreate(MainActivity.java:119)
  01-19 20:35:09.820: E/AndroidRuntime(1672):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  01-19 20:35:09.820: E/AndroidRuntime(1672):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

5 个答案:

答案 0 :(得分:1)

这对我有用,我不确定是什么问题。您可以再次交叉检查输入数据。

 List<String> suburl = new ArrayList<String>();
 suburl.add("alex 21 engineer");     
 suburl.add("xyz 21 engineer");      
 suburl.add("tim 21 engineer"); 
 suburl.add("gary 21 engineer");
 for(String temp : suburl) {
    String[] data = temp.split(" ");
    System.out.println("DATA 0 " +  data[0]);
    System.out.println("DATA 1 " + data[1]);
    System.out.println("DATA 2 " + data[2]);
}

答案 1 :(得分:1)

我认为可能并非所有字符串都有两个空格。只是不要做数据[x]之类的事情。使用另一个循环来使用这些字符串。

答案 2 :(得分:0)

如果您在ArrayList中设置数据,请执行以下操作:

   suburl.get(0) = "alex 21 engineer"
   suburl.get(1) = "mike 22 lawyer"
   suburl.get(2) = "sunny 26 deisnger"
   suburl.get(3) = "kim 24 painter"

我想您可能想要更改它并执行suburl.add("alex 21 engineer");

答案 3 :(得分:0)

它对我来说很好:

 public class TestClass {

        public static void main(String args[]) {
        ArrayList<String> suburl = new ArrayList<String>();


      suburl.add("alex 21 engineer");
   suburl.add("xyz 21 engineer"); 
   suburl.add("tim 21 engineer"); 
   suburl.add("gary 21 engineer");

       for(int i=0; i<suburl.size(); i++){

           String temp = suburl.get(i);
       String[] data = temp.split(" ");

         System.out.println(data[0]);
         System.out.println(data[1]);
         System.out.println(data[2]);
     }

结果:

   alex
21
engineer
xyz
21
engineer
tim
21
engineer
gary
21
engineer

答案 4 :(得分:0)

您必须将i<suburl.size();替换为i<suburl.size() - 1;