题目:
两个字符串比较,如:abcdefg,25abdfxx
返回:
位置0多出:25
位置2缺少:c
位置4缺少:e
位置6错误,应为:g
package com.it.threadDemo;
public class Main {
public static void main(String[] args) {
String s1="abceadefg";
String s2="25abcdfxx";
myMethod(s1,s2);
}
public static void myMethod(String s1, String s2){
char[] arr1= s1.toCharArray();
char[] arr2= s2.toCharArray();
//对应s1字符在s2中的位置位置
int copy=0;
for (int i = 0; i < arr1.length; i++) {
//获取当前字符值
String one= String.valueOf(arr1[i]);
//获取字符在s2中的位置
int num=s2.indexOf(one);
if(num<0){//如果不存在证明缺少或者错误
if(i==arr1.length-1){//最后一位不一致直接提示错误
System.out.println("位置" + i + "错误,应为:" + one);
}else if(arr1[i+1]==arr2[copy+1]){//s1当前索引后面一位与s2当前索引后一位致证明错误了
System.out.println("位置" + i + "错误,应为:" + one);
}else {//后一位不一致证明缺少了
System.out.println("位置" + i + "缺少:" + one);
//当缺少时s2的索引不再增加
copy--;
}
}else{
/**
* 通常情况下第一次出现的位置小于当前索引
* 但当出现abcdabc,25abcdbc时
* 此时s1走到d索引处,s2的copy值也走到了d索引处,
* 就会出现a小于copy值的情况
*/
if(num>copy) {//通常情况
String str = s2.substring(copy, num);
System.out.println("位置" + i + "多出:" + str);
copy = num;
}else if(num<copy){//此时就要判断是错误还剩减少了
if(i==arr1.length-1){//最后一位不一致直接提示错误
System.out.println("位置" + i + "错误,应为:" + one);
}else if(arr1[i+1]==arr2[copy+1]){//s1当前索引后面一位与s2当前索引后一位致证明错误了
System.out.println("位置" + i + "错误,应为:" + one);
}else {//后一位不一致证明缺少了
System.out.println("位置" + i + "缺少:" + one);
//当缺少时s2的索引不再增加
copy--;
}
}
}
//s2的索引也要随着s1自增
copy++;
}
}
}
结果图: