Java 怎么演示StringBuilder charAt, setCharAt, getChars and reverse 方法用法

2019年3月29日18:32:45 评论 129

1.简介

StringBuilder 的 charAt、setCharAt、 getChars 和 reverse,这四个方法怎么用,请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
public class StringBuilderMethod1 {
	public static void main(String[] args) {
		StringBuilder stringBuilder = new StringBuilder("Hello World");

		System.out.printf("StringBuilder = %s\n", stringBuilder.toString());
		System.out.printf("索引为0字符是: %s\n索引为4字符是: %s\n\n", stringBuilder.charAt(0), stringBuilder.charAt(4));

		char[] charArray = new char[stringBuilder.length()];
		stringBuilder.getChars(0, stringBuilder.length(), charArray, 0);
		System.out.print("所有字符: ");

		for (char character : charArray)
			System.out.print(character);

		stringBuilder.setCharAt(0, 'h');
		stringBuilder.setCharAt(6, 'T');
		System.out.printf("\n\n更改字符后StringBuilder = %s", stringBuilder.toString());
		stringBuilder.reverse();
		System.out.printf("\n\n反向后 StringBuilder = %s\n", stringBuilder.toString());
	}
}

3.结果

4.总结

charAt 获取指定索引的字符; setCharAt 设置指定索引的字符; getChars 获取字符数组; reverse 对内容反向。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: