Insert space after every one or two characters in string

时光毁灭记忆、已成空白 提交于 2021-01-27 17:24:49

问题


I need to write code to correct user input. The input is a mathematical expression in infix form. In order for my calculations to be correct, i need each operand spaced away from the operator.

Can you please help me write a method that will provide the following expected results.

Expected input: 13*21-5+33 Expected Output: 13 * 21 - 5 + 33

Research I have done: I could only find out how to add spaces between every character in the string and that will not work for calculating expressions with double digit values. Ie: 1 3 * 2 1 - 5 + 3 3. How to insert Space after every Character of an existing String in Java?

Thanks


回答1:


This solution normalizes the whitespace around each operator.

return expr.replaceAll("(?<=\\d)\\s*([-+/*])\\s*(?=\\d)", " $1 ");



回答2:


Look for digits using regex then surround them with spaces:

string.replaceAll("\\d+", " $0 ").trim(); // trim in case numbers are first/last


来源:https://stackoverflow.com/questions/10549013/insert-space-after-every-one-or-two-characters-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!