java 字符串按单词倒序输出

String str = "hi,hello world !";
 
//分割符
char[] splits = ", ".toCharArray();
Set<Character> splitCharSet = new HashSet<Character>();
for(char split:splits){
    splitCharSet.add(split);
}


StringBuilder reverseStr = new StringBuilder();
StringBuilder rsIndex = new StringBuilder();
Character indexChar;
for(int i=str.length()-1;i>-1;i--){
    indexChar = Character.valueOf(str.charAt(i));
    if(!splitCharSet.contains(indexChar)){
        rsIndex.append(indexChar);
    }else{
        reverseStr.append(rsIndex.reverse()).append(indexChar);
        rsIndex.delete(0, rsIndex.length());
    }
}
reverseStr.append(rsIndex.reverse());
System.out.println(reverseStr);

猜你喜欢

转载自uwangshan.iteye.com/blog/2296099