[英](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.