Java String 字符串

本文深入探讨 Java 中 String 类的实例化方法及常用操作,包括字符串的长度获取、替换、分割等实用技巧,并介绍如何利用 format 方法创建格式化的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值