Search code examples
javaregexstringtoken

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

Solution

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