gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:08:30 26 4
gpt4 key购买 nike

我不知道如何改进我的代码,因为当我在 "small Oleg" 之间放入两个空格时,它显示 "contains",但它是下降。因为“small Oleg”不等于“small Oleg”。也许不 split 就能解决?

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

关于java - 不使用 String 方法 - contains、indexOf、lastIndexOf 确定子字符串是否在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59505465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com