![](/img/trans.png)
[英]To check if a given string contains a substring without using contains or indexOf method
[英]Without using the String methods - contains, indexOf, lastIndexOf determine whether the substring is in the string
我不知道如何改进我的代码,因为当我在"small Oleg"
之间放入两个空格时,它显示"contains"
,但它是falls。 因为"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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.