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