Replace multiple characters in a string in Java

后端 未结 4 422
暗喜
暗喜 2020-12-22 07:26

I have some strings with equations in the following format ((a+b)/(c+(d*e))).

I also have a text file that contains the names of each variable, e.g.:

4条回答
  •  北海茫月
    2020-12-22 08:14

    Using a hashmap and iterating over the string as A Boschman suggested is one good solution.

    Another solution would be to do what others have suggested and do a .replaceAll(); however, you would want to use a regular expression to specify that only the words matching the whole variable name and not a substring are replaced. A regex using word boundary '\b' matching will provide this solution.

    String variable = "a";
    String newVariable = "velocity";
    str.replaceAll("\\b" + variable + "\\b", newVariable);
    

    See http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html

提交回复
热议问题