不使用 String 方法 - contains、indexOf、lastIndexOf 确定子字符串是否在字符串中



我不知道如何改进我的代码,因为当我在"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

最新更新