Java基础复习:StringBuilder小练习

练习:用StringBuilder 或StringBuffer:
把字符串“ABCDE”,转变成字符串“A,B,C,D”

 

public class StringBuilderTest {
	public static void main(String[] args) {
		
		StringBuilder sb = new StringBuilder("ABCDE");
		System.out.println("Before:"+sb);
		/**
		 * 1.StringBuilder -> String -> char[]
		 * 2.清空StringBuilder对象sb
		 * 3.将char[]中的内容依次加入sb中
		 * 4.删除最后一个','
		 */
		char[] cs = sb.toString().toCharArray();
		sb.delete(0, sb.length());
		for (char c : cs) {
			sb.append(c).append(',');
		}
		sb.deleteCharAt(sb.length()-1);
		System.out.println("After:"+sb);
	}
}

你可能感兴趣的:(JAVA)