0

I'm trying to extract the letters for the variables in a String "equation". Then save it to a String array called variables. However, when I print the variables array it is full of "empty containers"

How do I make it so that there are no empty spaces in the String[] variables containers?

String equation = "(a+2)/3*b-(28-c)";

String[] variables = equation.split("[+-/*0-9()]");

for(int i = 0 ; i < variables.length; ++i)
{
    System.out.println(variables[i]);
}
Toto
  • 89,455
  • 62
  • 89
  • 125
Carl C
  • 135
  • 8

2 Answers2

0

Given that your equation may have nested content, a single regex solution may not be optimal. Instead, I recommend using a pattern matcher, and just scanning the entire equation for letter variables:

String equation = "(a+2)/3*b-(28-c)";
String pattern = "[A-Za-z]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(equation);

while (m.find()) {
     System.out.println("Found a variable: " + m.group(0));
}

Found a variable: a
Found a variable: b
Found a variable: c

Note: This solution assumes you only want the variable names themselves, and you don't care about things like prefixes or coefficients.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

First replace all non-variable characters( matched by [+*-\\/0-9)(]) with empty string then change it to char array, try this one

String equation="(a+2)/3*b-(28-c)";
char[] variables= equation.replaceAll("[+*-\\/0-9)(]","").toCharArray();        

  for(int i = 0 ; i < variables.length; ++i)
{
    System.out.println(variables[i]);
}
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25