gpt4 book ai didi

java - 在Java中合并两个数组以保持顺序并使用第一个数组的唯一空白值

转载 作者:行者123 更新时间:2023-12-01 16:47:45 25 4
gpt4 key购买 nike

我有两个数组。我需要为后面的代码留出空白。

两个数组都有共同的值,并且共同的值应该是有序的。

这里有 AlphaBetaPhiGamma。两个数组之间都有空格。

String[] a = { " ", "Alpha", "Beta", "Phi", " ", "Gamma" };
String[] b = { "Alpha", " ", "Beta", "Phi", "Gamma", " " };

输出应考虑第一个数组,即由于数组的第一个元素 a"",因此输出以 Blank 开头。第二个数组的 AlphaBeta 之间的空白以及 Gamma 之后的空白应保持不变,因为它是第二个数组的一部分。此外,由于在第一个数组中,aPhiGamma 之间还有另一个 "",这不会出现在第二个数组 b 因此也会添加到输出中。两个数组的顺序必须保持相同,但位置会因 "" 的插入而改变。

预期输出:

[ " ", "Alpha", " ", "Beta", "Phi", " ", "Gamma", " " ]

普通合并很简单,并且有很多示例。不过,这是我目前还无法弄清楚的事情。

任何提示或示例都会有帮助。

抱歉,这不知何故是重复的帖子。

最佳答案

您可以按如下方式进行:

import java.util.Arrays;

public class Main {
public static void main(String[] args) {
int i, j, k;
String[] a = { " ", "Alpha", "Beta", "Phi", " ", "Gamma" };
String[] b = { "Alpha", " ", "Beta", "Phi", "Gamma", " " };

// Target array
String[] c = new String[a.length + b.length];

// Copy the elements from both the source arrays to the target array
for (i = 0; i < a.length && i < b.length; i++) {
add(c, a[i]);
add(c, b[i]);
}

// Copy the remaining elements from the first source array
for (k = i; k < a.length; k++) {
add(c, a[k]);
}

// Copy the remaining elements from the second source array
for (k = i; k < b.length; k++) {
add(c, b[k]);
}

// Discard null elements
c = trim(c);

// Display the target array
System.out.println(Arrays.toString(c));
}

static void add(String[] arr, String s) {
int i;
if (" ".equals(s)) {
// Find the position of first null
for (i = 0; arr[i] != null && i < arr.length; i++) {
// Do nothing
}

// Replace null with " "
arr[i] = s;
return;
}

// Return if the string already exists
for (i = 0; arr[i] != null && i < arr.length; i++) {
if (arr[i].equals(s)) {
return;
}
}

// Replace null with the string
arr[i] = s;
}

static String[] trim(String[] arr) {
int i;

// Find the position of first null
for (i = 0; arr[i] != null && i < arr.length; i++) {
// Do nothing
}

return Arrays.copyOf(arr, i);
}
}

输出:

[ , Alpha,  , Beta, Phi,  , Gamma,  ]

关于java - 在Java中合并两个数组以保持顺序并使用第一个数组的唯一空白值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61743897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com