2015-12-02 91 views
1

我已經寫了一個程序來比較兩個字符串,並返回相同的字母。不過,我也只想只打印一次普通字符。 (如 「辣」 和 「狗仔隊」 將返回 「PRI」如何檢查兩個字符串是否具有相同的字母,但只打印一次常用字母?

import java.util.Scanner; 
public class Q2{ 
    public static void main(String[] args){ 
     Scanner kbd = new Scanner(System.in); 
     System.out.print("Enter a word: "); 
     String x = kbd.nextLine(); 
     System.out.print("Enter a word: "); 
     String y = kbd.nextLine(); 
     System.out.println("Common character/s between " + x + " and " + y + " is/are " + join(x, y)); 
    } 
    public static String join(String x, String y){ 
     String q="";//define q 
     String z="";//define z 
     String big;//define big 
     String small;//define small 
     if (x.length()>y.length()){//figuring out which is big and which is small 
     big = x; 
     small = y; 
     } 
     else { 
     big = y; 
     small = x; 
     } 
     for(int i=0;i<small.length();i++){   
     char chbig = big.charAt(i); 
     if (small.lastIndexOf(chbig)!=-1){ 
      q=q+chbig;//define string with all same letters(duplicates included) 
     } 
     } 
     for(int i=0;i<q.length();i++){ 
     char chq = q.charAt(i); 
     if (q.lastIndexOf(chq)!=-1||q.lastIndexOf(chq)==-1){ 
      z=z+chq;//define string(duplicates excluded) 
     } 
     } 
     return z; 
    } 
} 

回答

2

1兩店集

2比較兩套

代碼:

public static String join(String x, String y){ 

    Set<Character> cx=new HashSet<Character>(); 
    Set<Character> cy=new HashSet<Character>(); 

    for (int k=0;k<x.length();k++) 
     cx.add(x.charAt(k)); 

    for (int k=0;k<y.length();k++) 
     cy.add(y.charAt(k)); 

    String result=""; 

    for (Character common: cx) 
     if (cy.contains(common)) 
      result+=common; 

    return result; 
} 
相關問題