我有一个代表计数“1,125,854”的字符串。
我想检查每千位小数后是否存在“,”。
例如125,854 和 1,125,854
我写了以下代码
import java.text.DecimalFormat;
import java.text.Format;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class CountComma {
public static void main(String[] args) {
String str = "1,125,854";
int count = 0;
String revStr = new StringBuilder(str).reverse().toString();
System.out.println("Reverse String: " + revStr);
List<Integer> format = new ArrayList<Integer>();
for (char ch : revStr.toCharArray()) {
System.out.println(ch);
if (ch == ',') {
count = count + revStr.indexOf(ch);
format.add(count);
}
}
System.out.println("Count: " + count);
System.out.println(format.toString());
}
}
This code gives output :
Reverse String: 458,521,1
4
5
8
,
5
2
1
,
1
Count: 6
[3, 6]
有人可以建议更好的方法吗?
谢谢
最佳答案
如果您只想检查数字字符串是否具有正确的逗号格式,那么您可以使用此单行代码:
String str = "1,125,854";
boolean isCorrect = str.matches("\\d{1,3}(,\\d{3})*");
更新:
如果您想让正则表达式更加与区域设置无关,您可以首先根据当前区域设置获取数千个分组分隔符。例如,如果在 servlet 中执行此检查,您可以尝试以下操作:
Locale currentLocale = httpServletRequest.getLocale();
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(currentLocale);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
char separator = symbols.getGroupingSeparator();
然后
boolean isCorrect = str.matches("\\d{1,3}(" + separator + "\\d{3})*");
关于java - 检查 count 是否在每一千之后包含 ,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41161834/