gpt4 book ai didi

Java分割字符串来获取值

转载 作者:行者123 更新时间:2023-12-01 12:01:09 25 4
gpt4 key购买 nike

我试图分割一个字符串来获取集合中的值,例如我有这个字符串:

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

接下来我用逗号分隔并插入到类的数组列表中:

ArrayList<SomeClass> someClass = new SomeClass<SomeClass>();
someClass.add(new SomeClass("215018", "738", "25094548"));

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

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

感谢任何帮助:)

最佳答案

这是一些试运行代码:

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 + ")";
}
}
}

关于Java分割字符串来获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com