我有两个字符串 字符串1 =“奉上帝的仁慈仁慈的名义。” 字符串2 =“以仁慈的上帝的名义”
我想将字符串2的每个单词与字符串1匹配。我使用了下面的代码,但在上述情况下无法正常工作
private void printDiff(final Context context, String sentence1, String sentence2) {
String[] array1 = sentence1.split(" ");
String[] array2 = sentence2.split(" ");
SpannableStringBuilder sb = new SpannableStringBuilder(sentence1);
for (int i = 0; i < array1.length; i++) {
int colorRes;
if (i < array2.length) {
colorRes = array1[i].equalsIgnoreCase(array2[i]) ? R.color.colorPrimary : R.color.colorAccent;
} else {
colorRes = R.color.black;
}
int startIndex = getStartIndexOf(array1, i);
int endIndex = startIndex + array1[i].length();
sb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
public static int getStartIndexOf(String[] array, int index) {
int count = 0;
for (int i = 0; i < index; i++) {
count += array[i].length();
count++;
}
return count;
}
谁能帮我
我想要这样的输出。因为所有字符都匹配
答案 0 :(得分:0)
您可以将String转换为字符数组,并可以按字符进行匹配
s1 = s1.replacereplace(" ", "");
s1 = s1.replacereplace(",", "");
s2 = s2.replacereplace(" ", "");
char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
int j=0;
for(int i=0; <a.length; i++){
if(a[i]==b[j]){
}
j++;
}
答案 1 :(得分:-1)
尝试使用此代码来检查您的字符串的差异
public class TestActivity extends AppCompatActivity {
String string1 = "In the name of God, the Gracious, the Merciful.";
String string2 = "In the name of God the Gracious the mercifuls";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
List<String> stringList = new ArrayList<>(Arrays.asList(string2.split(" "))); // Split the string into list
// compare the list with the source of the string, if match put into the list of result
List<String> result = stringList.stream().filter(new Predicate<String>() {
@Override
public boolean test(String s) {
// return string1.contains(s); // case sensitive
return Pattern.compile(Pattern.quote(s), Pattern.CASE_INSENSITIVE).matcher(string1).find(); // case insensitive
}
}).collect(Collectors.toList());
// check the match results
if(result.size()<stringList.size()){
Log.d("test", "onCreate: not match");
}else{
Log.d("test", "onCreate: match");
}
}
}
希望可以帮助您解决问题
因此可以使用上面的代码来编辑gradle。打开您的app.gradle并将其放入gradle
android {
compileSdkVersion 28
defaultConfig {
.....
}
buildTypes {
release {
.....
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}