我有字符串,我试图拆分文本并设置其格式
输入为 67.9200 2 3
输出将为 6 7.9 200
规则
1) split from the right to left based on the digits passed.
2) when split contains "." then add 1 to it .
3) if anything is remaining will just show in the front.
示例 67.9200 2 3
1. 3 (digits) -> will take the last 200
2. 2 (digits) -> will take 7.9 (since it has ".")
3. 6 -> Remaining will show (6)
任何建议或解决方案将不胜感激
答案 0 :(得分:1)
您可以从右开始扫描字符串,并将其继续存储在StringBuilder中,直到捕获到n1(3)个字符为止;每当遇到点时,跳过计数,一旦n1变为零,请添加空格并继续。对n2(2)应用相同的策略,在StringBuilder中拥有最终字符串后,只需反转字符串即可获得输出。这是一个示例程序。
public static void main(String[] args) {
String str = "67.9200";
int n1 = 2;
int n2 = 3;
StringBuilder sb = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
if (n2 > 0) {
char c = str.charAt(i);
sb.append(c);
if (c != '.') {
n2--;
if (n2 == 0) {
sb.append(" ");
}
}
} else if (n1 > 0) {
char c = str.charAt(i);
sb.append(c);
if (c != '.') {
n1--;
if (n1 == 0) {
sb.append(" ");
}
}
} else {
sb.append(str.charAt(i));
}
}
System.out.println(sb.reverse().toString());
}
这将提供以下输出,
6 7.9 200