String类

Posted by t298 on May 30, 2020

String类

字符串属于对象,java中提供了String类来操作字符串。

创建字符串

String类中有11种构造方法,这些方法提供了不同的参数来初始化字符.

注意:String类是不可以改变的。

创建字符串最简单的方法:

1
String greeting = "创建字符串";

提供一个字符数组参数:

1
2
3
4
5
6
7
public class test_mian {
    public static void main(String[] args) {
        char [] helloArray = {'r','e','b','b','o','t'};
        String helloSring = new String(helloArray);
        System.out.println(helloSring);
    }
}

字符串长度

用于获取有关对象的信息的方法称之为访问器方法。

String的一个访问器方法是length(),它返回字符串对象包含的字符数。

1
2
3
 String site = "3.14159265357";
        System.out.println(site.length());
        //13

格式化字符串

1
2
3
4
5
6
7
8
float fl =  1.3f;
       int a = 2;
       String b = "3";
       System.out.printf("浮点型变量的值为 " +
                "%f, 整型变量的值为 " +
                " %d, 字符串变量的值为 " +
                "is %s", fl, a, b);
        //浮点型变量的值为 1.300000, 整型变量的值为  2, 字符串变量的值为 is 3

更多方法查询API。