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