简体   繁体   中英

How to extract only the letters from string equation Java

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]);
}

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.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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