除了一个字符外,比较两个字符串的最简单方法是什么?

时间:2014-11-27 16:02:21

标签: java string

我是java的新手。

有人能告诉我这是比较两个字符串的最简单方法吗?

像:

'test' 'text'  //only one character different

应该返回true

==============================

喜欢输入:

'test' 'txxt' //two character different return false

应该返回false

我知道我们可以与for循环进行比较。还有其他办法吗? 谢谢你的帮助。 :)

2 个答案:

答案 0 :(得分:4)

假设字符串大小相同,这是一个解决方案。对于不均匀的字符串长度,需要稍微更改此解决方案

boolean compareStrings(String str1, String str2) {
    if (str1.length() != str2.length())
        return false;
    int differences = 0;
    for (int i = 0; i < str1.length(); i++) {
        if(str1.charAt(i) != str2.charAt(i))
            if(++differences > 1)
                return false;
    }
    //if the execution is here, then there are 0, or 1 differences, so return true
    return true;
}

答案 1 :(得分:0)

试试这个方法。 它应该适用于每个字符串组合,但根据使用情况,可能需要进行性能调整。

public static boolean compare(String s1, String s2) {
    if((s1 != null && s2==null) || (s1 == null && s2!=null)){
        //exact one is null
        return false;
    }
    if((s1 == null && s2==null) ||  s1.equals(s2)){
        //both are null or equal
        return true;
    }
    if(Math.abs(s1.length() - s2.length()) > 1){
        //A different length of more than one is more than one difference, right ?
        return false;
    }
    //Here you have two different strings. Maybe one is a character larger than the other.
    if(s1.length() != s2.length()) {
        //They differ in length, so they must be equal in the first minLen charcaters. 
        int minLen = Math.min(s1.length(), s2.length());
        return s1.substring(0,minLen).equals(s2.substring(0,minLen));
    }

    //Here you have two different strings of the same length.
    int diff = 0;
    for(int i = 0; i < s1.length() && diff < 2; i++){
        if(s1.charAt(i) != s2.charAt(i)){
            diff++;
        }
    }
    return diff < 2;
}