我不知道如何改进我的代码,因为当我在"small Oleg"之间放置两个空格时,它会显示"contains",但这是跌落。因为"small Oleg"不等于"small Oleg"。也许可以不拆分而解决?

import java.util.Arrays;

public class ContainsStr {
    public static void main(String[] args) {
        String s1 = "Hello small Oleg";
        String s2 = "small Oleg";

        String[] splitedS1 = s1.split("\\s+");
        String[] splitedS2 = s2.split("\\s+");
        String[] s3 = new String[splitedS2.length];
        for (int i = 0; i < splitedS1.length; i++) {
            for (int j = 0; j < splitedS2.length; j++) {
                if (splitedS1[i].equalsIgnoreCase(splitedS2[j])) {
                    s3[j] = splitedS2[j];
                }
            }
        }
        if (Arrays.equals(s3, splitedS2)) {
            System.out.println("Contains");
        } else {
            System.out.println("Not contains");
        }

    }
}

最佳答案

这将包含您自己的代码。

public static void main(String[] args) {
    String s1 = "Hello small Oleg";
    String s2 = "small Oleg";

    if (contains(s1, s2)) {
        System.out.println(s1 + " contains " + s2);
    }

    String[] splitedS1 = s1.split("\\s+");
    String[] splitedS2 = s2.split("\\s+");
    for (String s : splitedS1) {
        for (String ss : splitedS2) {
            if (contains(s, ss)) {
                System.out.println(s + " contains " + ss);
            }
        }
    }
}

public static boolean contains(String check, String compare) {
    if (check.length() < compare.length())
        return false;

    for (int i = 0; i < check.length(); i++) {
        for (int j = 0; j < compare.length(); j++) {
            if (check.charAt(i) == compare.charAt(j)) {
               if (checkTrail(i, j, check, compare)) {
                   return true;
               }
            }
        }
    }
    return false;
}

private static boolean checkTrail(int offset1, int offset2, String check, String compare) {
    for (int i = offset1; i < check.length(); i++) {
        for (int j = offset2; j < compare.length(); j++) {
            if (check.charAt(i) != compare.charAt(j)) {
                return false;
            }
        }
    }
    return true;
}


输出是

Hello small Oleg contains small Oleg
small contains small
Oleg contains Oleg

08-03 22:20