java字串陣列取別名,氣泡排序
/**
* 有一個字串陣列,我們要對這個字串陣列取別名,以使得字串陣列中,每個字串都是不相同的,規則如下
* 依次遍歷字串陣列,如果是第一次出現,則別名為本身,如果重複出現,則別名為字串加n,n從1開始遞增,
* 需要確保別名在已經便利的字串中不重複
* @author lenovo
*
*/
public class Ceshi {
public static void main(String[] args) {
String[] str ={"aaa","bbb","cccc","bbb","bbb","ddd","aaa"};
for (int i = 0; i < str.length; i++) {
int flag=0;
for (int j =i+1; j < str.length; j++) {
if(str[i]==str[j]){
flag++;
str[j]=str[j]+flag;
}
}
}
for (int i=0;i<str.length;i++){
System.out.print(str[i]+",");
}
}
}
列印結果:
aaa,bbb,cccc,bbb1,bbb2,ddd,aaa1,
//上面的結果可以但是String型別的字串比較不能用==,應該用equals
程式碼如下:
public class ArrString2 {
public static void main(String[] args) {
String[] strArra = {"abc","abc","abc","abcd","abcd","abcde","abc","abc","abc","abcd","abcd","abcde"};
String[] strOtherName = new String[strArra.length];
for (int i = 0; i < strArra.length; i++) {//遍歷原始陣列
for (int j = 0; j < strOtherName.length; j++) {//遍歷別名陣列
if(strArra[i].equals(strOtherName[j]) ){//在別名陣列中已經存在原始陣列中的某個元素
int count = 0;//計數變數
for (int i2 = 0; i2 < i; i2++) {//遍歷原始陣列中已經取過別名的的元素
if(strArra[i2].equals(strOtherName[j])){
count ++;//遍歷原始陣列中已經取過別名的的元素中和當前別名陣列中的元素值相等時,計數count加1
}
}
if(count > 0){
strOtherName[i] = strArra[i]+count;
}
break;
}else{
strOtherName[i] = strArra[i];
}
}
}
for (String string : strArra) {
System.out.print(string+" ");
}
System.out.println();
for (String string : strOtherName) {
System.out.print(string+" ");
}
}
}
執行結果:
原始資料: abc abc abc abcd abcd abcde abc abc abc abcd abcd abcde
執行後結果:abc abc1 abc2 abcd abcd1 abcde abc3 abc4 abc5 abcd2 abcd3 abcde1