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

来源:互联网 发布:四虎影库软件下载安装 编辑:程序博客网 时间:2024/06/05 16:06
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 ArrayListList<Character> list = new LinkedList<Character>();  //save the special character's index and itself//here,must use LinkedHashMap,rather than HashMapHashMap<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 positionSet<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 Stringsb = new StringBuilder(); //reset the StringBuilder//traverse the list,append all of the elements in the list to StringBuilderfor(char c:list){sb.append(c);}System.out.println(sb.toString()); }}
test result:
sdfthe key1: 3--the value1: *adfasdthe key1: 10--the value1: #ADADFsdfathe key1: 20--the value1: #fadthe key1: 24--the value1: $ajkldfthe key1: 31--the value1: @sasdthe key1: 36--the value1: %the key1: 37--the value1: /adfthe 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
原创粉丝点击