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

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]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值