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