gpt4 book ai didi

java - 如何在没有任何内置函数的情况下从java中的两个字符串中删除重复的字母表?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:46:17 24 4
gpt4 key购买 nike

这里我有两个字符串。由此,如何删除常见的字母/字符并存储在结果(第三个)字符串中?

<%
String[] firstString = {"google out"};
String[] secondString = {"stack overflow"};
String[] result={""};
for (int i = 0,k=0; i < firstString.length; i++,k++) {
for (int j = 0; j < secondString.length; j++) {
if (firstString[i].equalsIgnoreCase(secondString[j])) {
} else {
result[k]=result[j]+firstString[i];
out.println(result[k]);
}
}
}
%>

预期结果是:
g l e o u t s c k v f w

最佳答案

这是一种方法,

// Write a static helper method.
public static boolean contains(char[] in, int index, char t) {
for (int i = 0; i < index; i++) {
if (in[i] == t) return true;
}
return false;
}

public static void main(String[] args) {
String firstString = "google out"; // String(s) not String arrays
String secondString = "stack overflow";
// output cannot be larger then the sum of the inputs.
char[] out = new char[firstString.length() + secondString.length()];
int index = 0;
// Add all unique chars from firstString
for (char c : firstString.toCharArray()) {
if (! contains(out, index, c)) {
out[index++] = c;
}
}
// Add all unique chars from secondString
for (char c : secondString.toCharArray()) {
if (! contains(out, index, c)) {
out[index++] = c;
}
}
// Create a correctly sized output array.
char[] s = new char[index];
for (int i = 0; i < index; i++) {
s[i] = out[i];
}
// Just print it.
System.out.println(Arrays.toString(s));
}

输出是

[g, o, l, e,  , u, t, s, a, c, k, v, r, f, w]

编辑

如果您的预期输出不正确,而您实际上想要出现在两个字符串中的字符。

public static void main(String[] args) {
String firstString = "google out";
String secondString = "stack overflow";
char[] out = new char[firstString.length() + secondString.length()];
int index = 0;
for (char c : firstString.toCharArray()) {
if (contains(secondString.toCharArray(), secondString.length(), c)) {
out[index++] = c;
}
}
char[] s = new char[index];
for (int i = 0; i < index; i++) {
s[i] = out[i];
}
System.out.println(Arrays.toString(s));
}

哪些输出

[o, o, l, e,  , o, t]

编辑2

如果您真的想要与之相反,请将调用更改为 contains 并添加第二个循环(用于反向关系)-

    for (char c : firstString.toCharArray()) {
if (! contains(secondString.toCharArray(), secondString.length(), c)) {
out[index++] = c;
}
}
for (char c : secondString.toCharArray()) {
if (! contains(firstString.toCharArray(), firstString.length(), c)) {
out[index++] = c;
}
}

然后会输出

[g, g, u, s, a, c, k, v, r, f, w]

关于java - 如何在没有任何内置函数的情况下从java中的两个字符串中删除重复的字母表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783710/

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