从char数组中删除重复项的Java方法 [英] Java Method for removing duplicates from char array
问题描述
我有一个由用户(arrayInput[]
)填充的字符数组,其中包含一些字符,例如{b,d,a,b,f,a,g,a,a,f},我需要创建一个方法,该方法返回仅具有字符的第一个匹配项但按输入顺序的新char数组.该书还说:解决此问题的一种方法是创建一个布尔数组来跟踪要维护的字符!",但我无法想象布尔数组应如何与其他数组一起工作.
I have a char array filled by the user (arrayInput[]
) with some characters, like {b, d, a, b, f, a, g, a, a, f}, and I need to create a method which returns a new char array with only the first occurrence of the character, but in the order of input. The book also says "A way to solve this problem is to create a boolean array to keep track of the characters to mantain!", but I can't imagine how the boolean array should work with the other arrays.
主要问题是,如果arrayInput
包含一个特定字符,甚至是多少次,我都可以保存在一个布尔数组中,但是只能将一个很长的分支if-else创建为for,例如
The main problem is that I can save in a boolean array if arrayInput
contains a specific character, and even how many times, but only creating a very long ramified if-else into a for, like
if ((arrayOutput[i] == 'A') && (arrayControl[0] = false)) {
arrayControl[0] = true; }
其中,arrayOutput
是我要从该方法返回的数组,arrayControl[0]
是我在该方法中创建的布尔数组中的'A'值. A = 0,B = 1,... Z = 25,a = 26,b = 27,... 51 = z.对于每个单个字符(大写和小写),我都在数组中创建了一个位置,因此可以检查所有内容,但是现在我无法再进行任何操作了.我不知道如何将字符保存在arrayOutput
上,如何检查字符是否已经在arrayOutput
上,以及是否已经存在,数组会传递该特定字符并转到下一个字符.
where arrayOutput
is the array I want to return from the method, arrayControl[0]
is the value of 'A' in my boolean array I created into the method. A = 0, B = 1, ... Z = 25, a = 26, b = 27, ... 51 = z. For every single character, uppercase and lowercase, I created a place into the array, so I could check everything, but now I can't go any further. I don't know how to save the characters on arrayOutput
, how to check if a character is already on arrayOutput
and if it's already there, the array passes that specific character and go to the next one.
也请记住我是新手,所以我对Java知之甚少.请尽自己所能解释.提前致谢!
Also please remember I'm a newbie, so I know very little about Java. Please explain yourself the best you can. Thanks in advance!
推荐答案
这可能有效:
public static void main(String[] args) {
Main main = new Main();
char[] array = {'e','a','b','a','c','d','b','d','c','e'};
main.getCharArray(array);
}
private char[] getCharArray(char[] array) {
String _array = "";
for(int i = 0; i < array.length; i++) {
if(_array.indexOf(array[i]) == -1) // check if a char already exist, if not exist then return -1
_array = _array+array[i]; // add new char
}
return _array.toCharArray();
}
输出:
eabcd
Output:
eabcd
这篇关于从char数组中删除重复项的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!