java - 如何在JAVA中比较包含整数的字符串
问题描述
我在比较包含整数的字符串时遇到了一些问题。像A11
and A9
orBA230
和BA7
or之类的123
东西9
我知道当我想比较整数(它们是字符串类型)时,我需要传递给 Integer 并进行比较,但事实并非如此。
它还包含字母和数字,所以我不能传入整数。
当我比较A11
和A9
使用compareTo
方法时,它说A9
更大。当我与之相比123
时,9
它说9
更大。
有没有人遇到过这个问题?请你帮助我好吗?谢谢。
解决方案
/**
* Similar to compareTo method But compareTo doesn't return correct result for string+integer strings something like `A11` and `A9`
*/
private int newCompareTo(String comp1, String comp2) {
// If any value has 0 length it means other value is bigger
if (comp1.length() == 0) {
if (comp2.length() == 0) {
return 0;
}
return -1;
} else if (comp2.length() == 0) {
return 1;
}
// Check if first string is digit
if (TextUtils.isDigitsOnly(comp1)) {
int val1 = Integer.parseInt(comp1);
// Check if second string is digit
if (TextUtils.isDigitsOnly(comp2)) { // If both strings are digits then we only need to use Integer compare method
int val2 = Integer.parseInt(comp2);
return Integer.compare(val1, val2);
} else { // If only first string is digit we only need to use String compareTo method
return comp1.compareTo(comp2);
}
} else { // If both strings are not digits
int minVal = Math.min(comp1.length(), comp2.length()), sameCount = 0;
// Loop through two strings and check how many strings are same
for (int i = 0;i < minVal;i++) {
char leftVal = comp1.charAt(i), rightVal = comp2.charAt(i);
if (leftVal == rightVal) {
sameCount++;
} else {
break;
}
}
if (sameCount == 0) {
// If there's no same letter, then use String compareTo method
return comp1.compareTo(comp2);
} else {
// slice same string from both strings
String newStr1 = comp1.substring(sameCount), newStr2 = comp2.substring(sameCount);
if (TextUtils.isDigitsOnly(newStr1) && TextUtils.isDigitsOnly(newStr2)) { // If both sliced strings are digits then use Integer compare method
return Integer.compare(Integer.parseInt(newStr1), Integer.parseInt(newStr2));
} else { // If not, use String compareTo method
return comp1.compareTo(comp2);
}
}
}
}
推荐阅读
- c++ - 在 VS Code 中为 c++ 进行调试和发布配置
- jenkins - 如何在 jenkinsfile 中并行运行所有阶段
- java - 给定服务器的请求接受概率时如何对请求进行负载平衡?
- java - Java:给定一个整数数组,Java 如何确定使用哪个 remove() 方法?
- django - 在 Kubernetes pod 输出中将 Django 与 db.sqlite3 和持久卷一起使用 - django.db.utils.OperationalError:无法打开数据库文件
- javascript - 卡在 FreeCodeCamp 的 JS 计算器上
- java - Camel REST API 的 Junit 测试用例
- asp.net-mvc-4 - 即使我指定连接到不同的服务器,SQL Server 连接也总是使用本地数据库
- laravel - 无法在 laravel 8 的插件 Yajra Datatables 中从 mongodb 获取数据
- mongoose - GraphQL Dataloader 总是返回 null