简体   繁体   English

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

[英]How can I check if two strings have the same letters, but only print the common letters once?

I have written a program that compares two strings, and return the letters that are the same. 我编写了一个比较两个字符串并返回相同字母的程序。 However, I also want to only print the common characters only once. 但是,我也只想将常见字符打印一次。 (ex. "pepperoni" and "paparazzi" will return "pri" (例如,“ pepperoni”和“ paparazzi”将返回“ 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 store in two Set 1套2套

2 compare the two Sets 2比较两组

code: 码:

  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;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM