gpt4 book ai didi

java - 从字符串中提取数字和运算符

转载 作者:行者123 更新时间:2023-12-03 19:05:43 25 4
gpt4 key购买 nike

这是我编写的代码:

public static boolean isOperator(char op){
if (op == '+' || op == '-'
|| op == '*' || op == '/'
|| op == '^'
|| op == '(' || op == ')'){
return true;
}
return false;
}

public static boolean isOperand(char op){
String numbers = "0123456789.";
int a = numbers.indexOf(op);
return a >= 0;
}
public static void main(String []args){
String exp= "15+20+(3.84*25)*(78/3.8)";
LinkedList a = new LinkedList();

for (int i = 0; i < exp.length(); i++){
if (isOperator(exp.charAt(i))){
a.add(exp.charAt(i));
} else if (isOperand(exp.charAt(i))){
int k = i;
while (k < exp.length()){//I see the length of the number
if (isOperand(exp.charAt(k))){
k++;
} else {
break;
}
}
if (k != exp.length()-1){//if it's not ad the end
a.add(exp.substring(i, k));
} else {//if it's at the end I take all the remaining chars of the string
a.add(exp.substring(i));
}
i = k-1;//i must go back since the subtring second parameter is exclusive
}
}
System.out.println(a);
}//main

这是输出:

[15, +, 20, +, (, 3.84, *, 25, ), *, (, 78, /, 3.8), )]

这正是我想要的。如您所见,我将操作数和运算符分别放入一个维护字符串顺序的列表中。有没有更简单的方法?

最佳答案

Is there a way to do it in a simpler way?

是的,有。使用正则表达式。看看下面的代码和尝试根据您的输入运行它。

public static void main(String[] args) 
{
String exp = "15+20+(3.84*25)*(78/3.8)";
String regex = "(\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)])";

Matcher m = Pattern.compile(regex).matcher(exp);

LinkedList list = new LinkedList();

while (m.find()) {
list.add(m.group());
}

System.out.println(list);
}

我上面使用的正则表达式的解释:

"(\d+\.\d+)|(\d+)|([+-/*///^])|([/(/)])"

( double )或(整数)或(算术运算符)或(左/右括号)

关于java - 从字符串中提取数字和运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12871958/

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