简体   繁体   English

将字符串转换为用非数字字符拆分的双精度数组

[英]Convert an String to an array of doubles split with non-number characters

I know how I can split a string with a special character like space: 我知道如何分割带有特殊字符(如空格)的字符串:

String numbers = "22 14 10 8 70";
int [] n1 = new int [numbers.length()];
for(int n = 0; n < numbers.length(); n++) {
    n1[n] = Integer.parseInt(numbers.split(" ")[n]);
}

But I want to split String with any non-number(also negative sign and floating point) type of characters; 但是我想用任何非数字(也包括负号和浮点)类型的字符来分割String; like this string: 像这样的字符串:

String numbers = "22+14/10*8-70";

Try this algorithm Shunting-yard algorithm . 试试这个算法Shunting-yard算法

The shunting-yard algorithm is a method for parsing mathematical expressions specified in infix notation. 分流码算法是一种解析以中缀符号指定的数学表达式的方法。

You can also transform the available expression first to Postfix expression and then evaluate it. 您还可以先将可用表达式转换为Postfix表达式,然后对其求值。 Here is an explanation about it. 这里是一个解释。

String.split() can split over a regex string: String.split()可以分割成一个正则表达式字符串:

String numbers = "22+14/10*8-70";
String[] elements = numbers.split("[^0-9\\.]");
for(String e : elements)
{
    System.out.println("Element: " + e);
}

Prints: 打印:

Element: 22
Element: 14
Element: 10
Element: 8
Element: 70

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM