Java程序从给定的字符串中删除重复的字符
Set接口不允许重复的元素,因此,创建一个set对象,并尝试使用add()方法将每个元素添加到其中,以防元素重复,此方法返回false-
如果您尝试将数组的所有元素添加到Set中,则它仅接受唯一元素,因此将查找给定字符串中的重复字符
将其转换为字符数组。
尝试使用add方法将上面创建的数组的元素插入到哈希集中。
如果添加成功,则此方法返回true。
由于Set不允许重复元素,因此当您尝试插入重复元素时,此方法将返回0
打印这些元素
示例
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCharacters {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required string value ::");
String reqString = sc.next();
char[] myArray = reqString.toCharArray();
System.out.println("indices of the duplicate characters in the given string :: ");
Set set = new HashSet();
for(int i=0; i<myArray.length; i++){
if(!set.add(myArray[i])){
System.out.println("Index :: "+i+" character :: "+myArray[i]);
}
}
}
}输出结果
Enter the required string value :: malayalam indices of the duplicate characters in the given string :: Index :: 3 character :: a Index :: 5 character :: a Index :: 6 character :: l Index :: 7 character :: a Index :: 8 character :: m
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短