字符串排序,特殊字符位置不变

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

public class SortString {
	
	/**
	 * @param args
	 * @author Lzc
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//here,must use LinkedList,rather than ArrayList
		List<Character> list = new LinkedList<Character>();  
		//save the special character's index and itself
		//here,must use LinkedHashMap,rather than HashMap
		HashMap<Integer,Character> hm = new LinkedHashMap<Integer,Character>();
		StringBuilder sb = new StringBuilder();
		
		String str = "sdf*adfasd#ADADFsdfa#fad$ajkldf@sasd%/adf]";
		String[] strs = str.split("[^a-zA-Z]");
		int l = 0,i=0;
		for(String s: strs){
			System.out.println(s);
			sb.append(s);
			
			
			l += s.length(); 
//			if((l + i)>=(str.length()-s.length())) break;
			if(i>strs.length-1) break;
			
//			System.out.println(str.charAt(l + i)); 
//			hm.put(str.indexOf(str.charAt(l + i),l+i),str.charAt(l + i));  
			
			//
			hm.put(l+i,str.charAt(l + i));  
			System.out.println("the key1: " + (l + i) + "--the value1: " + str.charAt(l + i));
			
			i++;
		}
		
		char[] chars = sb.toString().toCharArray();
		Arrays.sort(chars);// sort the char array
//		list = Arrays.asList(chars);
//		System.out.println(list.size());
		for(char c:chars){
			list.add(c); //add the char to list
		}
		
		//traverse the hashmap,and add all of the special char to its original position
		Set<Entry<Integer,Character>> entrySet = hm.entrySet();
		for(Entry<Integer,Character> e:entrySet){
			System.out.println("the key2: " + e.getKey() + "--the value2: " + e.getValue());
			list.add(e.getKey(),e.getValue());
		}
		
		//list to String
		sb = new StringBuilder(); //reset the StringBuilder
		
		//traverse the list,append all of the elements in the list to StringBuilder
		for(char c:list){
			sb.append(c);
		}
		
		System.out.println(sb.toString()); 
	}

}
test result:
sdf
the key1: 3--the value1: *
adfasd
the key1: 10--the value1: #
ADADFsdfa
the key1: 20--the value1: #
fad
the key1: 24--the value1: $
ajkldf
the key1: 31--the value1: @
sasd
the key1: 36--the value1: %


the key1: 37--the value1: /
adf
the key1: 41--the value1: ]
the key2: 3--the value2: *
the key2: 10--the value2: #
the key2: 20--the value2: #
the key2: 24--the value2: $
the key2: 31--the value2: @
the key2: 36--the value2: %
the key2: 37--the value2: /
the key2: 41--the value2: ]
AAD*DFaaaa#aaadddddd#ddf$fffffj@klss%/sss]


你可能感兴趣的:(字符串排序,特殊字符位置不变)