Java:在两个字符串中查找常见字符

时间:2016-11-10 03:22:57

标签: java for-loop char indexof charat

我被要求编写一个程序,使用 indexOf(char)方法和 for循环在两个字符串中查找常见字符。这是我到目前为止的结果 - 输出仍然是空白的。

import java.util.Scanner;
public class ClassName {
   public static void main (String args []) {

   Scanner input = new Scanner (System.in);

   String a = "";
   String b = "";
   String c = "";

   System.out.print("Enter two words: ")
   a = input.nextLine();
   b = input.nextLine();

   for (int i = 0; i < a; i++){

      char ch = a.charAt(i);
      if (b.indexOf(ch) != -1){
         c = c+String.valueOf(ch);
         }
      }
System.out.print("Common letters are: "+c);
}

}

output here

我不确定从哪里开始。

感谢

3 个答案:

答案 0 :(得分:1)

您的代码会复制常见字符,例如,如果您将“开发者”与“程序员”进行比较,您的结果字符串将包含三次e字符

如果您不想要这种行为,我建议你也使用像这样的Set:

public class CommonCharsFinder {

    static String findCommonChars(String a, String b) {
        StringBuilder resultBuilder = new StringBuilder();
        Set<Character> charsMap = new HashSet<Character>();
        for (int i = 0; i < a.length(); i++) {
            char ch = a.charAt(i); //a and b are the two words given by the user
             if (b.indexOf(ch) != -1){
                 charsMap.add(Character.valueOf(ch));
             }
        }

        Iterator<Character> charsIterator = charsMap.iterator();
        while(charsIterator.hasNext()) {
            resultBuilder.append(charsIterator.next().charValue());
        }
        return resultBuilder.toString();
    }
    // An illustration here
    public static void main(String[] args) {
       String s1 = "developper";
       String s2 = "programmer";

       String commons = findCommonChars(s1, s2);
       System.out.println(commons);     
    }

}

示例的结果:

enter image description here

答案 1 :(得分:0)

公共类CommonCharFromTwoString {

public static void main(String args[])
{
   System.out.println("Enter Your String 1: ");
   Scanner sc = new Scanner(System.in);
   String str1 = sc.nextLine();
   System.out.println("Enter Your String 2: ");
   String str2 = sc.nextLine();

   Set<String> str = new HashSet<String>();
   for(int i=0;i<str1.length();i++){
       for (int j = 0; j < str2.length(); j++) {
          if(str1.charAt(i) == str2.charAt(j)){
              str.add(str1.charAt(i)+"");
          }
    }
   }

    System.out.println(str);
}

}

答案 2 :(得分:0)

public Set<Character> commonChars(String s1, String s2) {
    Set<Character> set = new HashSet<>();
    for(Character c : s1.toCharArray()) {
        if(s2.indexOf(c) >= 0) {
            set.add(c);
        }
    }
    return set;
}