我被要求编写一个程序,使用 indexOf(char) 方法和 for 循环 查找两个字符串中的公共(public)字符。这是我到目前为止所得到的 - 输出仍然是空白。
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);
}
}
我不知道该去哪里。
谢谢
最佳答案
您的代码将重复常见字符,例如,如果您将“开发人员”与“程序员”进行比较,您的结果字符串将包含三倍的 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);
}
}
示例结果:
关于Java:查找两个字符串中的共同字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519473/