一、String字符串的实例化
这两种方式是有区别:
这种方式实例化时,如果检测到常量池里存在该字符串常量,则JVM就不再创建新的String对象了。
二、String类中一些常见的方法
1、length()方法返回字符串的长度:
2、startsWith(String Value)判断字符串是否以Value开头。若是,则返回true;否则,返回false:
3、endsWith(String Value)判断字符串是否以Value结尾。若是,则返回true;否则,返回false:
4、
5、
6、
7、replaceAll()方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串:
public class Test {
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("匹配成功返回值 :" );
System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" ));
System.out.print("匹配失败返回值 :" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" ));
}
}
class Test {
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("匹配成功返回值 :" );
System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" ));
System.out.print("匹配失败返回值 :" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" ));
}
}
以上程序执行结果为:
匹配成功返回值 :runoob
匹配失败返回值 :www.google.com
:runoob
匹配失败返回值 :www.google.com
8、trim()方法用于删除字符串的头尾空白符:
public class Test {
public static void main(String args[]) {
String Str = new String(" www.runoob.com ");
System.out.print("原始值 :" );
System.out.println( Str );
System.out.print("删除头尾空白 :" );
System.out.println( Str.trim() );
}
}
class Test {
public static void main(String args[]) {
String Str = new String(" www.runoob.com ");
System.out.print("原始值 :" );
System.out.println( Str );
System.out.print("删除头尾空白 :" );
System.out.println( Str.trim() );
}
}
以上程序执行结果为:
原始值 : www.runoob.com
删除头尾空白 :www.runoob.com
: www.runoob.com
删除头尾空白 :www.runoob.com
9、split(String sign)返回一个数组,该数组由原始字符串根据sign拆分得到:
public class Test {
public static void main(String args[]) {
String str = new String("Welcome-to-Runoob");
System.out.println("- 分隔符返回值 :" );
for (String retval: str.split("-")){
System.out.println(retval);
}
}
以上程序执行结果为:
- 分隔符返回值 :
Welcome
to
Runoob
分隔符返回值 :
Welcome
to
Runoob
10、
11、
创建格式化字符串
我们知道输出格式化数字可以使用 printf() 和 format() 方法。
String 类使用静态方法 format() 返回一个String 对象而不是 PrintStream 对象。
String 类的静态方法 format() 能用来创建可复用的格式化字符串,而不仅仅是用于一次打印输出。
如下所示:
System.out.printf("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", floatVar, intVar, stringVar);
你也可以这样写
String fs;fs = String.format("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
" %s", floatVar, intVar, stringVar);