要注意此字符串不是给定的,是从键盘上读入的,我们还不知道要删除的是什么字母,必须先判断字符串重复出现的字母。
这是去重的完整代码
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入(连续相同数字将去重):");
String temp=input.next();
show(temp);
}
//去重方法
public static void show(String str){
char[] tempList=str.toCharArray(); //将得到的String型字符串转变为Char型字符
for (int i = 0; i < tempList.length-1; i++) { //循环数组
if (tempList[i]==tempList[i+1]) { //判断两个数是否相等,如果相等则去掉
tempList[i]=0; //如果相邻两数重复了 则为0 由于char是基本
tempList[i+1]=0; //类型,所以初始值为0,不过并不影响效果
}
}
for (int i = 0; i < tempList.length; i++) {
if (tempList[i]!=0) { //如果两数都不为0 则输出
System.out.print(tempList[i]);
}
}
}
令附上效果: