如何检查两个字符串是否具有相同的字母,但只打印一次常用字母?

时间:2015-12-02 18:12:00

标签: java string

我编写了一个比较两个字符串的程序,并返回相同的字母。但是,我也只想打印一次普通字符。 (例如"辣香肠"和#34;狗仔队"将返回" 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;
   }
}

1 个答案:

答案 0 :(得分: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;
 }