Java 程序从给定字符串中删除重复字符

java programming java8java technologies object oriented programming

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

相关文章