import java.util.Scanner;
public class CharDemo {
public static void main(String[] args) {
System.out.println("请输入一段字符串");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char[] cs = str.toCharArray();//字符串到字符数组
for (int i = 0; i < cs.length-1; i++) {
if(cs[i]=='a'){//提高性能,减少循环次数,如果字母是a就不管了,直接进行下次循环
continue;
}
boolean flag = false;//没有找到相同的字母 表示为false
for (int j = i+1; j < cs.length; j++) {
if(cs[i]== cs[j]){
cs[j]='a';//找到后,修改为字符'a'
flag = true;//找到了相同的字符就吧flag修改为true
}
}
if(flag){//如果找到了.那么就修改cs[i]也为字符'a'
cs[i] = 'a';
}
}
System.out.println(new String(cs));
}
}
运行测试
请输入一段字符串
abcdce
abadae
String str = "ddfsssg hi dq ";
String reg = "(.)\\1+";
str.replaceAll(reg,"a");