[英]Given an string (100*((2+12)/5))/14, how would you add spaces between each operator and number?
For example I want to go from this string例如我想从这个字符串 go
(100*((2+12)/5))/14
to this对此
( 100 * ( ( 2 + 12 ) / 5 ) ) / 14
You can do it as你可以这样做
"(100*((2+12)/5))/14".replaceAll("\\D", "$0 ").replaceAll("\\d+", "$0 ").trim();
Explanation:解释:
\D
specifies a non-digit character which will be replaced with the character plus space. \D
指定将替换为字符加空格的非数字字符。\d+
specifies an integer number which will be replaced with the number plus space.在该替换中, \d+
指定了一个 integer 数字,该数字将替换为数字加空格。trim()
.最后,尾随和前导空格将被trim()
删除。public class Main {
public static void main(String[] args) {
String expression = "(100*((2+12)/5))/14";
expression = expression.replaceAll("\\D", "$0 ").replaceAll("\\d+", "$0 ").trim();
System.out.println(expression);
}
}
Output: Output:
( 100 * ( ( 2 + 12 ) / 5 ) ) / 14
You can iterate over all characters, and then check if:您可以遍历所有字符,然后检查是否:
public static void main(String[] args)
{
String str = "(100*((2+12)/5))/14";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
sb.append(c);
if (i < str.length() - 1)
{
if ((Character.isDigit(c) && !Character.isDigit(str.charAt(i + 1))) || !Character.isDigit(c))
{
sb.append(" ");
}
}
}
System.out.println(sb.toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.