Java 拆分字符串以获取值

Java splitting a string to get values

我正在尝试拆分一个字符串以获取集合中的值,例如我有这个字符串:

215018,738,25094548 47137,77,1479107 80595,70,740157 38834,90,5419316 59382,82,2431554 865303,1,4 158088,44,56662 139671,61,325746 530224,5,410 783,99,14400482 268478,20,4981 577948,1,30 684122,1,40 222912,37,27987 598052,1,18 614235,1,40 69690,48,85643 235186,32,17801 329817,14,2179 118561,50,102391 380170,1,0 376338,1,0 374930,1,0 335953,1,0 -1,-1 -1,-1 -1,-1

我需要用空格分隔这个字符串,这样我就可以得到这个:

215018,738,25094548

接下来我用逗号分隔并插入到 class:

的数组列表中
ArrayList<SomeClass> someClass = new SomeClass<SomeClass>();
someClass.add(new SomeClass("215018", "738", "25094548"));

我需要为第一个字符串中的每个值执行此操作。 我还需要能够忽略字符串末尾的“-1”。

我无法理解执行此任务背后的逻辑和代码。

感谢任何帮助:)

这里有一些伪代码供您参考:

将它分成几个部分,使用带有此功能的“”字符,public String[] split(String regex),像这样

String[] splitBySpace = yourString.split(" "); 

这允许您使用空格拆分成数组。 X拿着一串字符串"x,y,z,a,b,c (etc) "。然后,再次调用相同的函数。

String[] splitbyComma = splitBySpace[i].split(",");  // this will split using the commas, run it in a for loop and save it somewhere

现在 y 包含填充了单个值的数组。添加到数组、数组列表或您选择在末尾使用的任何列表。

关于最后x里面的"-1"s at the end of your string; just don't use the last 3 indexes of the x array (since there will be 3 copies of "-1,-1"

添加到数组列表(假设列表是您的 ArrayList):

for (int i = 0; i < /* your end condition */; i++) {
    String[] splitByComma = splitBySpace[i].split(",");
    list.add(new someObj(splitByComma[0], splitByComma[1], splitByComma[2]));
}

下面是一些干货-运行代码:

public class Split
{
    public static void main (String[] args) {
      String SPACE_K = " ";
      String SEPARATOR_K = ",";

      String input = "15018,738,25094548 47137,77,1479107 80595,70,740157 38834,90,5419316 59382,82,2431554 865303,1,4 158088,44,56662 139671,61,325746 530224,5,410 783,99,14400482 268478,20,4981 577948,1,30 684122,1,40 222912,37,27987 598052,1,18 614235,1,40 69690,48,85643 235186,32,17801 329817,14,2179 118561,50,102391 380170,1,0 376338,1,0 374930,1,0 335953,1,0";
      String[] numbers = input.split(SPACE_K);
      for (int i=0; i<numbers.length; i++) {
        String number = numbers[i];
        String[] values = number.split("\"+SEPARATOR_K );
        if (values!=null && values.length==3) {
            Skill skill = new Skill(values[0], values[1], values[2]);
            System.out.println("\nCreated new object "+ skill.toString());
        }
      }
    }

    public static class Skill {
        private final String val1, val2, val3;

        public Skill(String in1, String in2, String in3)  {
          val1 = in1; val2 = in2; val3 = in3;
        }

        public String toString() {
          return "Skill ("+ val1 + ", " + val2 + ", " + val3 + ")";
        }        
    }
}