[英]Merge two String Arrays using only loops
我遇到一個我無法理解的簡單任務問題。 我有一個簡單的任務是創建一個合並兩個數組但不重復的算法,僅使用for循環...
到目前為止,這是我的代碼...
public static String[] mergeReps(String[] a1, String[] a2) {
// Create a new array with the full size (I'll remove the nulls later)
String[] retArray = new String[a1.length + a2.length];
// Copy of array a1 to the retArray
retArray = Arrays.copyOf(a1, a1.length);
// Test print...
System.out.println(Arrays.toString(retArray));
// loop to check if the indexes value are present in the a1 array
for (int i = 0; i < a1.length - 1; i++) {
for (int j = i + 1; j < a2.length; j++) {
// Condition to check if the value is duplicated
if (!(a1[j].equalsIgnoreCase(a2[i]))) {
retArray[i + a1.length] = a2[j];
}
}
}
return retArray;
}
我的問題是:我怎樣才能將a2 [0]與a1數組中的每個位置進行比較,並且只有在這樣做並知道其是否重復之后,才將其添加到retArray中?
嘗試使用此代碼段。 基本上,它使用集合的uniqueness屬性來編譯一組唯一的字符串值。 然后將其轉換為String []。
查看HashSets的javadocs,以獲取有關其工作方式的更多信息。
Set<String> result = new HashSet<String>();
for(String s : a1)
{
result.add(s);
}
for(String s : a2)
{
result.add(s)
}
return result.toArray(new String[result.size()]);
您可以使用此:
for(int nextItemOfSecondArray = a2.length -1; nextItemOfSecondArray >= 0; i--){
boolean checkIfAlreadyExists = false;
for(int i = 0; i < a2.length; i++){
if(a2[nextItemOfSecondArray].equalsIgnoreCase(a1[i])){
checkIfAlreadyExists = true;
break;
}
}
if(!checkIfAlreadyExists)
a1[a1.length] = a2[nextItemOfSecondArray];
}
假設a1和a2都沒有重復項,這是如何合並沒有重復項的數組:
public static String[] mergeReps(String[] a1, String[] a2) {
//validate the incoming arrays
if (a1 == null && a2 == null) {
System.err.println("error - input arrays are null");
return new String[]{};
} else if (a1 == null) {
return a2;
} else if (a2 == null) {
return a1;
}
int arrEffSize = 0;
boolean unique;
String s, sfinal;
String[] tempArray = new String[a1.length + a2.length];
//just copy a1 to the tempArray
System.arraycopy(a1, 0, tempArray, 0, a1.length);
arrEffSize = a1.length;
//add String objects from a2, if it isn't already there
for (int i=0; i < a2.length; i++) {
unique = true;
s = a2[i];
for (int j=0; j < arrEffSize; j++) {
sfinal = tempArray[j];
if (s.equalsIgnoreCase(sfinal)) {
unique = false;
break;
}
}
if (unique) {
tempArray[arrEffSize] = s;
arrEffSize++;
}
}
//create a new array with the appropriate size, then copy tempArray to it
String[] retArray = new String[arrEffSize];
System.arraycopy(tempArray, 0, retArray, 0, retArray.length);
return retArray;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.