Java程序删除给定字符串中的重复字符
该Set接口不允许重复元素,因此,创建一个Set对象,并尝试使用add()方法将每个元素添加到其中,如果元素重复,则此方法返回false -
如果您尝试将数组的所有元素添加到Set中,它只接受唯一元素,因此,要查找给定字符串中的重复字符。
问题陈述
给定一个字符串,编写一个Java程序来删除给定字符串中的重复字符 -
输入
TUTORIALSPOINT
输出
Indices of the duplicate characters in the given string :: Index :: 2 character :: T Index :: 10 character :: O Index :: 11 character :: I Index :: 13 character :: T
从给定字符串中删除重复字符的步骤
以下是从给定字符串中删除重复字符的步骤 -
- 导入所有必要的类。
- 将字符串转换为字符数组。
- 尝试使用add方法将上面创建的数组的元素插入到哈希集中。
- 如果添加成功,此方法返回true。
- 由于Set不允许重复元素,因此当您尝试插入重复元素时,此方法返回0
- 打印这些元素。
Java程序删除给定字符串中的重复字符
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 :: TUTORIALSPOINT Indices of the duplicate characters in the given string :: Index :: 2 character :: T Index :: 10 character :: O Index :: 11 character :: I Index :: 13 character :: T
代码解释
程序首先导入必要的类和接口:HashSet、Scanner和来自java.util包的Set。main方法初始化一个Scanner来读取用户的输入字符串,然后将其转换为字符数组。HashSet用于存储唯一字符,利用其不允许重复的特性。
程序使用for循环遍历字符数组,使用HashSet的add()方法尝试添加每个字符。如果字符已存在,add()返回false,程序打印索引和重复字符。此方法确保所有重复项都能被有效地识别和输出,利用HashSet来优化性能,避免重复元素。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP