如何在没有任何内置函数的情况下从java中的两个字符串中删除重复的字母? [英] How to remove duplicate alphabets from two strings in java without any builtin functions?
本文介绍了如何在没有任何内置函数的情况下从java中的两个字符串中删除重复的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里我有两个字符串。从那,我如何删除常见的字母/字符并存储在结果(第三)字符串?
Here I have two strings. From that, how can I remove common alphabets/characters and store in result(third) String?
<%
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]);
}
}
}
%>
预期结果为:
gleoutsckvfw
推荐答案
这是一种方法,
// 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]
编辑
如果您的预期输出不正确,你真的想要两个字符串中出现的字符。
If your expected output is incorrect, and you actually want the characters that appear in both Strings.
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
如果您真的想要与此相反,请将调用更改为包含
并添加第二个循环(用于反向关系) -
If you actually wanted the opposite of that, change the call to contains
and add a second loop (for the inverse relationship) -
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中的两个字符串中删除重复的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文