day14 Java 常用类 String类(二)


他们陪着我, 永远不寂寞
还有还有,一只大狼狗




一、String 类的转换功能

1.1 byte[] getBytes()

使用平台的默认字符集将此String编码为字节序列,将结果存储到新的字节数组中

String s = "HelloWorLD";
byte[] a = s.getBytes();
        for(int i = 0; i < a.length;i++){
    
    
            System.out.println(a[i] + " ");
        }
// 72 101 108 108 111 87 111 114 76 68
//打印 ascii码值

1.2 char[] toCharArray()

将此字符串转换为新的字符数组

String s = "HelloWorLD";
        char[] b = s.toCharArray();
        for(int i = 0; i < a.length;i++){
    
    
            System.out.print(b[i] + " ");
        }
//H e l l o W o r L D

1.3 static String valueOf(char[] chs)

字符数组转换成字符串

char[] c = {
    
    'f','g','h'};
System.out.println(String.valueOf(c));		//	fgh

1.4 static String valueOf(int i)

将int类型的数据转化成字符串

System.out.println(String.valueOf(100));		//	100

1.5 String toLowerCase()

将字符串内容全部转化成小写

String s = "HelloWorLD";
System.out.println(s.toLowerCase());		//	helloworld

1.6 String toUpperCase()

将字符串内容全部转化成大写

String s = "helloworld";
System.out.println(s.toUpperCase());		//	HELLOWORLD

1.7 String concat(String str)

将指定的字符串连接到该字符串的末尾。
将小括号里面的字符串拼接到调用方法的字符串后面

String s1 = "Hello";
String s2 = "World";
String s3 = "";
String s4 = null;
String s5 = s1.concat(s2);
Stirng s6 = s1.concat(s3);		
String s7 = s1.concat(s4);		

System.out.println(s5);		//HelloWord
System.out.println(s6);		//	Hello
System.out.println(s7);		//	NullPointerException



二、String 类的其他功能

1.1 String replace(char old,char new)

将字符串的 old 字符,全部替换成 new 字符

String s = "helloworld";
System.out.println(s.replace('e','a'));
// halloworld

1.2 String replace(String old,String new)

将字符串的 old 字符串,全部替换成 new 字符串

String s = "helloworld";
System.out.println(s.replace("owo","wow"));
//	hellwowrld

1.3 String trim()

去除字符串两空格

String s = "helloworld";
System.out.println(s);
System.out.println(s.trim());
//	 helloworld
//	helloworld

1.4 int compareTo(String str)

按字典顺序比较两个字符串

String s = "helloworld";
String s2 = "helloworld";
String s3 = "hello";
String s4 = "helloworldfgh";
String s5 = "abc";

System.out.println(s.compareTo(s2));		//	0	
System.out.println(s.compareTo(s3));		//	5
System.out.println(s.compareTo(s4));		//	-3
System.out.println(s.compareTo(s5));		//	-7

完全匹配时返回 0;
其中之一是另一个一的部分,返回两个字符串长度差;
不匹配时,返回两个字符ASCII码差
h的ASCII码值:104;a的ASCLL码值:97

1.5 int compareToIgnoreCase(String str)

按字典顺序比较两个字符串
不区分大小写,其余同 compareTo() 相同

String[] split(String regex)

将字符串按照指定内容分割,存储至新的字符串集合 split 中


总结

byte[] getBytes()

使用平台的默认字符集将此String编码为字节序列,将结果存储到新的字节数组中

char[] toCharArray()

将此字符串转换为新的字符数组

static String valueOf(char[] chs)

字符数组转换成字符串

static String valueOf(int i)

将int类型的数据转化成字符串

String concat(String str)

将指定的字符串连接到该字符串的末尾。
将小括号里面的字符串拼接到调用方法的字符串后面

String trim()

去除字符串两空格

猜你喜欢

转载自blog.csdn.net/qq_41464008/article/details/120661734