
java中,从键盘上读入一个字符串,如何删除此字符串中所有相同的字母。如读入的字符串为good,得到gd 20
这是去重的完整代码
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]);
}
}
}
令附上效果:
将字符串转化为字符数组
for(i=0; i<string.length; i++) //遍历整个字符数组,求出相同字母
for(j=i+1; j<string.length; j++)
if(c[i]==c[j]) c1[k++] = c[i]; //记录重复的字母(会有重复记录,不过没关系)
for(int i=0; i<k; i++){
string = string.replaceAll("c1[i]",""); //用replaceAll函数将重复的字母替换为空
}
System.out.println("请输入字符串!");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String input = br.readLine();
boolean flag = false;
for(int i=0;i<input.length();i++){
int num = input.charAt(i);
if(!(num>=65 && num<90) && !(num>=97 && num<=122)){
flag = true;
}
}
if(flag){
System.out.println("请输入有效字符");
}else{
if(input.length()==0){
System.out.println("字符不能为空!");
}else{
List strList = new ArrayList();
for(int j=0;j<input.length();j++){
for(int n=0;n<input.length();n++){
if(String.valueOf(input.charAt(j)).equals(String.valueOf(input.charAt(n))) && j!=n){
strList.add(String.valueOf(input.charAt(j)));
}
}
}
for(int m=0;m<strList.size();m++){
input = input.replaceAll(String.valueOf(strList.get(m)), "");
}
System.out.println("处理后的字符串为"+input);
}
}
} catch (Exception e) {
e.printStackTrace();
}