有两个字符串:
str1= "#1.jpg#2.gif#3.jpg#4.jpg ";
str2= "#1.jpg#3.gif ";
合并后的字符串为:1.jpg#2.gif#3.gif#4.jpg
有没有简单点的方法,我自己写了好几个循环
------解决方案--------------------
public static String combine(String s1, String s2) {
if (s1 == null || s1.trim().length() == 0) {
return s2;
}
if (s2 == null || s2.trim().length() == 0) {
return null;
}
String[] a1 = s1.split( "# ");
String[] a2 = s2.split( "# ");
int index2 = 0;
int index1 = 0;
StringBuffer result = new StringBuffer();
for (; index1 < a1.length; index1++) {
String temp1 = a1[index1];
if (temp1 == null || temp1.trim().length() == 0) {
continue;
}
if(index2> =a2.length){
break;
}
for (; index2 < a2.length; index2++) {
String temp2 = a2[index2];
if (temp2 == null || temp2.trim().length() == 0) {
continue;
}
if (temp1.compareTo(temp2) < 0) {
result.append( "# ").append(temp1);
break;
} else if (temp1.compareTo(temp2) == 0) {
result.append( "# ").append(temp1);
index2++;
break;
} else {
result.append( "# ").append(temp2);
}
}
}
for (; index1 < a1.length; index1++) {
result.append( "# ").append(a1[index1]);
}
for (; index2 < a2.length; index2++) {
result.append( "# ").append(a2[index2]);
}
return result.toString().substring(1);
}