我需要一些帮助,我有两个字符串,我希望第一次出现常见的子字符串。
1st String : abacdefghi
2nd String : abaciopiss
我想获得子串
substring : abac
谢谢大家。
答案 0 :(得分:0)
它可能不是最佳解决方案,但我的尝试是找到每个字符串中的第一个匹配字符,然后继续检查以下字符是否仍然相同:
private static String extractFirstEqual(String a, String b) {
//Split your string into an array of characters
String[] arr = a.split("");
String[] brr = b.split("");
StringBuilder result = new StringBuilder();
//Iterate over both arrays
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < brr.length; j++) {
//Find first matching character
if (arr[i].equals( brr[j])) {
//While there are more characters in both arrays and the characters keep matching, append them
// to the result
while (arr[i].equals(brr[j]) && i < arr.length && j < brr.length) {
result.append(arr[i]);
i++;
j++;
}
return result.toString();
}
}
}
return result.toString();
}