本篇文章展示了Java中String类的用法,代码简明扼要容易理解,如果在日常工作遇到这个疑问。希望大家通过这篇文章,找到解决疑问的办法。

一、String的创建方法

直接创建

String str = "我是 java-er.com";
System.out.println(str);

拷贝创建

String str = new String("我是 java-er.com");
System.out.println(str);
3.用数组构建

char[] arr = {'J','a','v','a'};
String arrString = new String(arr);
System.out.println(arrString);

二、String格式化

输出格式化数字可以使用 printf() 和 format() 方法。

printf() 方法为了一次打印输出格式化数字
2.String类的静态方法 format() 能用来创建可复用的格式化字符串,而不仅仅是用于一次打印输出。

float f = 2.4f;
int i = 5;
String s = "字符串";
System.out.printf("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", f, i, s);

String fs = String.format("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", f, i, s);

System.out.println("\n我可以再次打印:" + fs);
输出

浮点型变量的值为 2.400000, 整型变量的值为 5, 字符串变量的值为 is 字符串
我可以再次打印:浮点型变量的值为 2.400000, 整型变量的值为 5, 字符串变量的值为 is 字符串
https://java-er.com/blog/java-string-study/

java StringBuffer,StringBuilder,String自身连接效率对比

关于Java中String类的用法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果喜欢这篇文章,不如把它分享出去让更多的人看到。