如何在运算符处分割字符串 [英] How to split string at operators

查看:128
本文介绍了如何在运算符处分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java创建计算器。

Im creating a calculator in Java.

如果我让用户输入一个字符串,例如:

If i have the user enter a string such as:

7+4-(18/3)/2

到目前为止,我不得不让用户在每个数字或运算符之间输入一个空格。
我如何从给定的字符串创建一个数组,其中该字符串按数字或运算符进行拆分,因此在这种情况下,数组为:

So far i have had to have the user enter a space between each number or operator. How would i create an array from the given string where the string is split at either number or an operator so in this case the array would be:

[7, +, 4, -, (, 18, /, 3, ), /, 2]

(该数组的类型为String)

(The array is of type String)

任何帮助将不胜感激

谢谢:)

推荐答案

您尚未指定要对数组执行的操作。如果您真的想对表达式求值,那么已经可以使用该库了。您可以使用其中之一。但是,如果您只想像显示的那样一个数组,那么我也不建议使用正则表达式。您可以编写自己的解析器方法,如下所示:

You haven't specified what you want to do with the array. If you really want to evaluate the expression, then there are already libraries available for that. You can use one of them. But if you only want an array like the one you have shown, then also I wouldn't suggest to use regex. You can write your own parser method like below:

public static String[] parseExpression(String str) {
    List<String> list = new ArrayList<String>();
    StringBuilder currentDigits = new StringBuilder();

    for (char ch: str.toCharArray()) {
        if (Character.isDigit(ch)) {
            currentDigits.append(ch);
        } else {
            if (currentDigits.length() > 0) {
                list.add(currentDigits.toString());
                currentDigits = new StringBuilder();
            }
            list.add(String.valueOf(ch));
        }
    }

    if (currentDigits.length() > 0)
        list.add(currentDigits.toString());

    return list.toArray(new String[list.size()]);
}

现在称呼为:

String str = "7+4-(18/3)/2";
System.out.println(Arrays.toString(parseExpression(str)));

,您将得到结果。

这篇关于如何在运算符处分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆