[英]Java: String to integer array
I have a string, which is a list of coordinates, as follows: 我有一个字符串,它是坐标列表,如下所示:
st = "((1,2),(2,3),(3,4),(4,5),(2,3))"
I want this to be converted to an array of coordinates, 我希望将其转换为坐标数组,
a[0] = 1,2
a[1] = 2,3
a[2] = 3,4
....
and so on. 等等。
I can do it in Python, but I want to do it in Java. 我可以用Python来做,但是我想用Java来做。 So how can I split the string into array in java??
那么如何在Java中将字符串拆分为数组呢?
It can be done fairly easily with regex, capturing (\\d+,\\d+)
and the looping over the matches 使用正则表达式,捕获
(\\d+,\\d+)
并在匹配项中循环,可以相当轻松地完成
String st = "((1,2),(2,3),(3,4),(4,5),(2,3))";
Pattern p = Pattern.compile("\\((\\d+),(\\d+)\\)");
Matcher m = p.matcher(st);
List<String> matches = new ArrayList<>();
while (m.find()) {
matches.add(m.group(1) + "," + m.group(2));
}
System.out.println(matches);
If you genuinely need an array, this can be converted 如果您确实需要数组,可以将其转换为
String [] array = matches.toArray(new String[matches.size()]);
Alternative solution: 替代解决方案:
String str="((1,2),(2,3),(3,4),(4,5),(2,3))";
ArrayList<String> arry=new ArrayList<String>();
for (int x=0; x<=str.length()-1;x++)
{
if (str.charAt(x)!='(' && str.charAt(x)!=')' && str.charAt(x)!=',')
{
arry.add(str.substring(x, x+3));
x=x+2;
}
}
for (String valInArry: arry)
{
System.out.println(valInArry);
}
If you don't want to use Pattern-Matcher; 如果您不想使用Pattern-Matcher;
This should be it: 应该是这样:
String st = "((1,2),(2,3),(3,4),(4,5),(2,3))";
String[] array = st.substring(2, st.length() - 2).split("\\),\\(");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.