关闭

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

616人阅读 评论(0) 收藏 举报
分类:
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]


0
0

猜你在找
【套餐】Hadoop生态系统零基础入门
【套餐】嵌入式Linux C编程基础
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【套餐】深度学习入门视频课程——唐宇迪
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】计算机视觉原理及实战——屈教授
【直播】机器学习之凸优化——马博士
【直播】机器学习&数据挖掘7周实训--韦玮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:354614次
    • 积分:4226
    • 等级:
    • 排名:第7168名
    • 原创:131篇
    • 转载:24篇
    • 译文:5篇
    • 评论:59条
    最新评论