[英](java) how to split a number on parts and then compare them to each other
我想知道如何在部件上拆分数字然后将它们相互比较
例如,我有一组数字
989010
990009
991008
992992
993006
994005
995004
我希望将每个数字分成两部分 - >>
if it's 989010 -- it will be like '989' and '010'.
在那之后,我想我可以比较两个字符串,对吧?
我的意思是,
'989' != '010' true
'990' != '009' true
'992' != '992' false
似乎我应该使用split函数,但是我混淆了如何仅分开两个部分而不是更多部分
提前致谢!
String str = "989010";
System.out.println(str.substring(0, 3).equals(str.substring(3,6)));
你可以这样做有几种方法。
String.substring
可以给你两个字符串,也可以分割数字
int number = 123456;
int firstPart = number / 1000;
int secondPart = number - firstPart * 1000;
编辑
对不起 - 匆匆忙忙。
为了弥补这一点,我将再次证明任何值得解决的问题都可以通过regex
的(通常令人费解的)语言来解决:
final String[] strings = new String[]{"123123", "123456"};
final Pattern pattern = Pattern.compile("([\\d]{3})\\1");
for (final String string : strings) {
final Matcher matcher = pattern.matcher(string);
if (matcher.matches()) {
System.out.println(string + " matches.");
}
}
输出:
run:
123123 matches.
BUILD SUCCESSFUL (total time: 0 seconds)
哈,甚至需要0 seconds
。
Long number = 989010L;
String text = number.toString();
String firstPart = text.substring(0,3);
String secondPart = text.substring(3);
Long firstNumber = Long.parseLong(firstPart);
Long secondNumber = Long.parseLong(secondPart);
System.out.println(firstNumber == secondNumber);
看这个
public static void main(String[] args) {
String[] values = { "989010", "990009", "991008", "992992", "993006", "994005", "995004" };
for(String value : values) {
String firstPart = value.substring(0, 3);
String secondPart = value.substring(3);
if(firstPart.equals(secondPart)) {
System.out.println(firstPart + " equals " + secondPart);
}
}
}
`String s = "931492";
int first = Integer.parseInt(s.substring(0, s.length()/2));
int second = Integer.parseInt(s.substring(s.length()/2));
if (first != second)
{
System.out.println("Not equal");
}`
编辑:对,我正在比较错误的子串,抱歉。 在比较Java中的字符串时,也应该使用equals()。 我更新了我的代码以生成两个Integer。 可能会提供额外的比较功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.