简体   繁体   English

Java:搜索两个字符串之间的第一个公共字符

[英]Java: Search the first common character between two strings

I'm in trouble to solve this problem.我很难解决这个问题。 I have to create a method called cercaCarattere that takes in input two strings, compares them and, if it finds a character (the first one, corresponding) must return it, otherwise must return a '*'.我必须创建一个名为 cercaCarattere 的方法,它接受输入的两个字符串,比较它们,如果找到一个字符(第一个,对应的)必须返回它,否则必须返回一个“*”。 Plus, in the main, I must read two strings in a loop, until the character returned by the method and the last character of the first string are different.另外,在 main 中,我必须循环读取两个字符串,直到方法返回的字符与第一个字符串的最后一个字符不同。

This is the code that I wrote这是我写的代码

public class prova {

public static char cercaCarattere(String str1, String str2) {
    boolean isCommon = false;
    char letter;
    for(int i=0; i<str1.length() && i<str2.length(); i++) {
        if(str1.charAt(i) == str2.charAt(i)) {
            isCommon = true;
            letter = str1.charAt(i);
        } else {
            isCommon = false;
            letter = '*';
        }
    }

    return letter;
}

public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
    String str1, str2;

    System.out.println("Inserire la stringa");
    str1 = stdin.nextLine();
    System.out.println("Inserire la stringa");
    str2 = stdin.nextLine();

    cercaCarattere(str1, str2);
}

In the method, I thought to write a for to read both the strings and check for every character if is the same in both and, if so, to return it, but that return gives me an error because says "letter" is not initialized.在该方法中,我想写一个 for 来读取两个字符串并检查每个字符是否相同,如果相同,则返回它,但是该返回给了我一个错误,因为“字母”未初始化. How can I solve?我该如何解决?

I cannot use Hashset, arrays or other.我不能使用 Hashset、数组或其他。

Make the following two changes :进行以下两项更改:

In your cercaCarattere() once you find the first occurence you can return early.在您的cercaCarattere()一旦您找到第一次出现,您就可以提前返回。 Also the method can be simplified to :该方法也可以简化为:

public static char cercaCarattere(String str1, String str2) {
    char letter = '*';
    for (int i = 0; i < str1.length() && i < str2.length(); i++) {
        if (str1.charAt(i) == str2.charAt(i)) {
            return str1.charAt(i);
        } 
    }
    return letter;
}

And, use the value returned by the method to print it out并且,使用方法返回的值打印出来

System.out.println(cercaCarattere(str1, str2));

Ciao Andrea, the code is not work because: Ciao Andrea,代码不起作用,因为:

  • you must return after letter = str1.charAt(i);你必须在letter = str1.charAt(i);之后返回letter = str1.charAt(i);
  • you can delete isCommon because you don't use it你可以删除isCommon因为你不使用它

So the code becames:所以代码变成了:

public static char cercaCarattere(String firstString, String secondString) {
    char letter = '*';
    for (int i = 0; i < firstString.length() && i < secondString.length(); i++) {
        if (firstString.charAt(i) == secondString.charAt(i)) {
            return firstString.charAt(i);
        } 
    }
    return letter;
}

Java 8 stream solution: Java 8 流解决方案:

  • to find matching char at corresponding position在相应位置找到匹配的char
    public static char cercaCarattere(String str1, String str2) {
        return IntStream.range(0, Math.min(str1.length(), str2.length()))
            .filter(i -> str1.charAt(i) == str2.charAt(i))
            .mapToObj(str1::charAt)
            .findFirst()
            .orElse('*');
    }
  • to find first matching char at any position:在任何位置找到第一个匹配的char
    public static char cercaCarattere(String str1, String str2) {
        return str1.chars().mapToObj(c1 -> (char) c1)
            .filter(c1 -> str2.chars().mapToObj(c2 -> (char) c2).anyMatch(c2 -> c1 == c2))
            .findFirst()
            .orElse('*');
    }

They way it is written your code would not the task, even if the compiler did not complain about the variable.他们的方式是编写您的代码不会执行任务,即使编译器没有抱怨该变量。 The reason compiler spits the error, is because in case both of your strings have zero length, letter indeed stays uninitialized.编译器吐出错误的原因是,如果您的两个字符串的长度都为零,则letter确实保持未初始化状态。 The second problem is that you should break the loop as soon as you found the match, but the code does not.第二个问题是您应该在找到匹配项后立即中断循环,但代码没有。 The right way is this:正确的方法是这样的:

char letter = '*';
for(int i=0; i<str1.length() && i<str2.length(); i++) {
    if(str1.charAt(i) == str2.charAt(i)) {
        letter = str1.charAt(i);
        break;
    } 
}

return letter;

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

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