[英]Removing duplicates from sorted Char array
I am trying to take the string below, convert it to an array, sort the array, then take out any duplicates. 我正在尝试采用下面的字符串,将其转换为数组,对数组进行排序,然后取出所有重复项。 I have gotten to the sorted part, but when I run this in hopes for the duplicates being removed, it seems to print position instead of the value there.
我已经进入排序部分,但是当我运行此操作以希望删除重复项时,它似乎在打印位置而不是那里的值。
This is also counting spaces as length, giving me a length of 59 for this. 这也将空格计为长度,因此我的长度为59。
Can I get some help figuring out what I need to change? 我可以得到一些帮助来确定我需要更改的内容吗? Thank you all!
谢谢你们!
import java.util.*;
public class Challenge208 {
public static void main(String[] args) {
String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
Arrays.sort(chars);
System.out.println(chars);
int current = chars[0];
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (current == chars[i] && !found) {
found = true;
}else if (current != chars[i]) {
System.out.print(" " + current);
current = chars[i];
found = false;
}
}
System.out.print(" " + current);
}
}
current
should be type char
not int
. current
应为char
not int
类型。 To get rid of the spaces, you could print if current
is not a space. 要消除空格,如果
current
不是空格,则可以打印。
而不是使用数组,您可以使用treeset。它将具有排序的顺序,并且没有重复项。但是,如果在这种情况下,您需要数组,那么您的当前变量是int而不是char,并且您不会删除任何重复项.you只是打印,只要您找到该char,即使该项目没有任何重复项且仅用于char [0]
You are not getting the index of the number but its ascii value. 您没有得到数字的索引,而是得到它的ascii值。 For more details: http://www.asciitable.com/ But solution is as follows:
有关更多详细信息: http : //www.asciitable.com/但是解决方案如下:
import java.util.*;
public class Challenge208 {
public static void main(String[] args) {
String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
char[] results = new char[10];
Arrays.sort(chars);
System.out.println(chars);
char current = chars[0];
int size = 0;
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (current == chars[i] && !found) {
found = true;
}else if (current != chars[i]) {
System.out.print(" " + current);
size++;
current = chars[i];
found = false;
}
}
System.out.print(" " + current);
System.out.print("\n"+size);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.