首页 > 解决方案 > 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]);
}

标签: javaregexstringtoken

解决方案


首先用空字符串替换所有非可变字符(匹配[+*-\\/0-9)(])然后将其更改为char数组,试试这个

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

推荐阅读