一个字符串由a-z和逗号.组成,要求反转字符串,以逗号.分割。不能使用split
public class Test { public static void main(String[] arg0){ String s = "asd....dfa...d.fee.c"; System.out.println(new Test().getReverseStr(s)); } public String getReverseStr(String s){ if(s==null) { return null; } char[] chars = s.toCharArray(); String temp = ""; Stack<String> stack = new Stack(); for (int i = 0; i < chars.length; i++) { if(chars[i]!='.') { if(temp.contains(".")) { stack.push(temp); temp = ""; } temp+=chars[i]; }else { if(!temp.contains(".")) { stack.push(temp); temp = ""; } temp+=chars[i]; } } stack.push(temp); String reverse = ""; while (!stack.isEmpty()){ reverse+=stack.pop(); } return reverse; } }
例:字符串s="asd....dfa...d.fee.c";
输出: