[英]Removing duplicates from sorted Char array
我正在尝试采用下面的字符串,将其转换为数组,对数组进行排序,然后取出所有重复项。 我已经进入排序部分,但是当我运行此操作以希望删除重复项时,它似乎在打印位置而不是那里的值。
这也将空格计为长度,因此我的长度为59。
我可以得到一些帮助来确定我需要更改的内容吗? 谢谢你们!
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
应为char
not int
类型。 要消除空格,如果current
不是空格,则可以打印。
而不是使用数组,您可以使用treeset。它将具有排序的顺序,并且没有重复项。但是,如果在这种情况下,您需要数组,那么您的当前变量是int而不是char,并且您不会删除任何重复项.you只是打印,只要您找到该char,即使该项目没有任何重复项且仅用于char [0]
您没有得到数字的索引,而是得到它的ascii值。 有关更多详细信息: 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.