我想通過一個int[]
數組,並從中獲取子串值。例如,如果我的陣列是{1,2,1,4}
我希望能夠取出{1,2}
並將其與{1,4}
比較,或者我想將{1,2,1}
與{4,1,2}
進行比較。我的問題是,我想通過一個數組,並查看是否「substring」值再次顯示在數組中,但以相反的順序。在java中獲取數組的子串
我知道你有substring(包括,排他)的字符串是否有任何類似的數組或我必須將數組轉換爲字符串才能做這樣的事情?
我想通過一個int[]
數組,並從中獲取子串值。例如,如果我的陣列是{1,2,1,4}
我希望能夠取出{1,2}
並將其與{1,4}
比較,或者我想將{1,2,1}
與{4,1,2}
進行比較。我的問題是,我想通過一個數組,並查看是否「substring」值再次顯示在數組中,但以相反的順序。在java中獲取數組的子串
我知道你有substring(包括,排他)的字符串是否有任何類似的數組或我必須將數組轉換爲字符串才能做這樣的事情?
難道你不能簡單地確定數組中你想使用的數字集和位置形式,然後從下一個索引開始搜索序列中的第一個或最後一個數字,然後一旦找到它,然後開始搜索下一個號碼?
即[1,4,5,1,3,1,4,2]我們想要取[1,4]並且在陣列中發現它是相反的。
從索引2開始:[5]!= 1 - > [1] == 1 - > [3]!= 4 - > [3]!= 1 - > [1] == 1 - > [ 4] == 4,成功。
您可以簡單地比較數組中的每個數字和最後一個數字,如果它們匹配,則進入一個循環,檢查下一個數字是否與最後一個數字相同,等等。 其他人從循環中出來並說不匹配。
Or
您可以在給定數組中以相反順序遍歷來檢查您的設置。 可能有點冗長,但對所有人都適用。
如果字符串表達式不需要其他的東西,你可以(也可能)只使用數組中的數字。
這是檢查int數組中的區間的對稱性的函數。你可以改變ini的參數,結束而不是ini,如果你願意,可以相應地改變算法,當然。
public boolean checkSymmetry(int[] data, int ini, int length) {
// Iterates the interval of interest
for (int i=ini; i<ini+length-1; i++) {
// The symmetric position: start from the end (length),
// come back i positions and sum one (because arrays starts on 0)
int symmetricPos = data.length - i - 1;
if (data[i] != data[symmetricPos]) {
return false;
}
}
return true;
}
您可以將整數數組轉換爲字符串,但Arrays.toString()
函數會將其直接轉換。由此,從{1, 2, 2, 1}
到[1, 2, 2, 1]
。有關更多信息,請參閱here。
// strTest -> [1, 2, 2, 1]
String strTest = Arrays.toString(test);
但是,您可以刪除方括號,逗號和空格。通過使用String.replace()
或String.replaceAll()
函數。從[1, 2, 2, 1]
到1221
。
// strTest -> 1221
strTest = strTest.replaceAll(", ", "").replace("[", "").replace("]", "");
如果要扭轉現有字符串,可以使用StringBuffer.reverse()
函數。
// use StringBuffer to acquire reverse of text
StringBuffer buffer = new StringBuffer(strTest.substring(2, 4)); // it will get '21' of '1221'
String revStrTest = buffer.reverse().toString(); // from '21' to '12'
下面是完整的代碼:
// from array of test
int[] test = { 1, 2, 2, 1};
// strTest -> [1, 2, 2, 1]
String strTest = Arrays.toString(test);
// strTest -> 1221
strTest = strTest.replaceAll(", ", "").replace("[", "").replace("]", "");
System.out.print(strTest.substring(0, 2) + " == " + strTest.substring(2, 4) + " : ");
// checks 12 and 21
if(strTest.substring(0, 2).equals(strTest.substring(2, 4)))
System.out.println("EQUAL");
else
System.out.println("NOT EQUAL");
// use StringBuffer to acquire reverse of text
StringBuffer buffer = new StringBuffer(strTest.substring(2, 4)); // it will get '21' of '1221'
String revStrTest = buffer.reverse().toString(); // from '21' to '12'
System.out.print(strTest.substring(0, 2) + " == " + revStrTest + " : ");
// checks 12 of strTest and 12 of revStrTest
if(strTest.substring(0, 2).equals(revStrTest))
System.out.println("EQUAL");
else
System.out.println("NOT EQUAL");
什麼叫 「反向」 順序是什麼意思?爲什麼要比較「{1,2,1}」和「{4,1,2}」,以及如何?請分享更多具有明確要求和理解的例子。 – Braj 2015-04-01 04:45:42
'java.util.Arrays。copyOfRange'(專用於每個基本元素類型或對象)以相同的順序給出一部分,如String.substring。 AFAICT沒有直接的方法來反轉數組。 – 2015-04-01 05:58:18