有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何用正则表达式拆分这个表达式?

我正在解一个方程,但我想用常数来编程我的解

分解成常数的方法。问题是,当我拆分时,一个带有负常数的方程将产生一个带有常数绝对值的数组。如何在仍然使用正则表达式的情况下实现减号

如果输入是ax+by=c,那么输出应该是{a,b,c}

有用的好处:有没有办法删除拆分时创建的空元素。例如,如果我键入等式2x+3y=6,我将得到一个包含元素{2,,3,,6}的“原始”数组

代码:

public static int[] decompose(String s)
{
    s = s.replaceAll(" ", "");

    String[] termRaw = s.split("\\D"); //Splits the equation into constants *and* empty spaces.
    ArrayList<Integer> constants = new ArrayList<Integer>(); //Values are placed into here if they are integers.
    for(int k = 0 ; k < termRaw.length ; k++)
    {
        if(!(termRaw[k].equals("")))
        {
            constants.add(Integer.parseInt(termRaw[k]));
        }

    }
    int[] ans = new int[constants.size()];

    for(int k = 0 ; k < constants.size(); k++) //ArrayList to int[]
    {
        ans[k] = constants.get(k);
    }
    return ans;
}

共 (2) 个答案

  1. # 1 楼答案

    解决这个问题的一般策略是用算子分解输入方程,然后在循环中提取系数。然而,有几个边缘情况需要考虑:

    • 加号(+)是每个减号的前缀,它既不是第一项也不是第一项
    • 拆分后,通过查看空字符串来检测正系数
    • 分裂后,通过看到减号来检测负系数


    String input = "-22x-77y+z=-88-10+33z-q";
    input = input.replaceAll(" ", "")             // remove whitespace
                 .replaceAll("=-", "-");          // remove equals sign
                 .replaceAll("(?<!^)-", "+-");    // replace - with +-, except at start of line
    // input = -22x+-77y+z+-88+-10+33z+-
    
    String[] termRaw = bozo.split("[\\+*/=]");
    // termRaw contains [-22x, -77y, z, -88, -10, 33z, -]
    
    ArrayList<Integer> constants = new ArrayList<Integer>();
    // after splitting,
    // termRaw contains [-22, -77, '', -88, -10, 33, '-']
    for (int k=0 ; k < termRaw.length ; k++) {
        termRaw[k] = termRaw[k].replaceAll("[a-zA-Z]", "");
        if (termRaw[k].equals("")) {
            constants.add(1);
        }
        else if (termRaw[k].equals("-")) {
            constants.add(-1);
        }
        else {
            constants.add(Integer.parseInt(termRaw[k]));
        }
    }
    
  2. # 2 楼答案

    如果您使用的是java8,那么您可以使用以下一行方法:

    public static int[] decompose(String s) {
        return Arrays.stream(s.replaceAll("[^0-9]", " ").split("\\s+")).mapToInt(Integer::parseInt).toArray();
    }
    

    演示:

    1。输出

    [2, 3, 6]
    

    2。代码

    import java.util.*;
    
    public class HelloWorld {
        public static void main(String args[]) {
            String s = "2x+3y=6";
            int[] array = decompose(s);
            System.out.println(Arrays.toString(array));
        }
    
        public static int[] decompose(String s) {
            return Arrays.stream(s.replaceAll("[^0-9]", " ").split("\\s+")).mapToInt(Integer::parseInt).toArray();
        }
    }