Java学习String 类

xiaoxiao2021-02-28  91

/* Java String 类 字符串广泛应用于Java编程中,在Java中字符串属于对象,Java提供了String类来创建和操作字符串。 */ //创建字符串 String greeting = "菜鸟"; //String类是不可以改变的解析 String s = "Google"; System.out.println("s = " + s); s = "Runoob"; System.out.println("s = ") + s) /* 从结果上看是改变了,但为什么门说String对象是不可变的呢? 原因在于实例中的 s 只是一个 String 对象的引用,并不是对象本身,当执行 s = "Runoob"; 创建了一个新的对象 "Runoob",而原来的 "Google" 还存在于内存中。 */ public class StringDemo{ public static void main(String args[]){ char[] helloArray = {'r','u','n','n','o','o','b'}; String helloString = new String(helloArray); System.out.println(helloString); } } /* String类是不可改变的,如果需要对字符串做很多更改,那么硬选择使用 StringBuffer/StringBuilder类。 */ /* 字符串长度: 获取字符串长度的方法是length()方法,它返回字符串对象包含的字符数 */ public class StringDemo{ public static void main(String args[]){ String site = "www.runoob.com"; int len = site.length(); System.out.println("菜鸟教程网址长度:" + len); } } //连接字符串 //2种方法:concat方法和”+”连接字符串方法 public class StringDemo{ public static void main(String args[]){ String string1 = "菜鸟教程地址"; System.out.println("1、" + string1 + "www.runoob.com"); System.out.println("2、".concat(string1).concat("www.runoob.com")); } } //创建格式化字符串 format或者printf() public class StringDemo{ public static void main(String args[]){ String string1 = "菜鸟教程地址"; //字符串连接“+”方法 System.out.println("1、" + string1 + "www.runoob.com"); //字符串连接“concat”方法 System.out.println((string1).concat("www.runoob.com")); //创建格式化字符串-printf()方法 System.out.printf("浮点型变量的的值为 " + "%f, 整型变量的值为 " + " %d, 字符串变量的值为 " + "%s", 2.55, 5, string1); //创建格式化字符串-format方法 String fs; fs = String.format("浮点型变量的的值为 " + "%f, 整型变量的值为 " + " %d, 字符串变量的值为 " + " %s", 12.2, 5, string1); System.out.println(fs); } }
转载请注明原文地址: https://www.6miu.com/read-22027.html

最新回复(0)