2.29.2020
字符串建立的四种格式
package com.liuermeng.string;
/*
java.lang.String类代表字符串。
API当中说:Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。
其实就是说:程序当中所有的双引号字符串,都是String类的对象。(就算没有new,也照样是。)
字符串的特点:
1. 字符串的内容永不可变。【重点】
2. 正是因为字符串不可改变,所以字符串是可以共享使用的。
3. 字符串效果上相当于是char[]字符数组,但是底层原理是byte[]字节数组。
创建字符串的常见3+1种方式。
三种构造方法:
public String():创建一个空白字符串,不含有任何内容。
public String(char[] array):根据字符数组的内容,来创建对应的字符串。
public String(byte[] array):根据字节数组的内容,来创建对应的字符串。
一种直接创建:
String str = "Hello"; // 右边直接用双引号
注意:直接写上双引号,就是字符串对象。
*/
public class Demo01String {
public static void main(String[] args) {
String str1=new String();//建立空字符串
System.out.println("第一个字符串:"+str1);
char[] ch={'h','e','l','l','o'};
String str2=new String(ch);//根据字符数组创建字符串
System.out.println("第二个字符串:"+str2);
byte[] bt={65,66,67};//注意这里实际上是将整数转换成ASCII码表中对应的字符
String str3=new String(bt);// 根据字节数组创建字符串
System.out.println("第三个字符串:"+str3);
String str4="hello"; // 直接创建
System.out.println("第四个字符串:"+str4);
}
}
第一个字符串:
第二个字符串:hello
第三个字符串:ABC
第四个字符串:hello
同样的字符串也可以转化成字符数组和byte数组
package com.liuermeng.string;
/*
String当中与转换相关的常用方法有:
public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。
public byte[] getBytes():获得当前字符串底层的字节数组。
public String replace(CharSequence oldString, CharSequence newString):
将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。
备注:CharSequence意思就是说可以接受字符串类型。
*/
import java.util.Arrays;
public class Demo02StringToCharArray {
public static void main(String[] args) {
String str1="hello";
char[] ch=str1.toCharArray();
System.out.println(Arrays.toString(ch));//将字符数组转化为字符串输出(按默认格式:[元素1,元素2...])
byte[] bt=str1.getBytes();
System.out.println(Arrays.toString(bt));
String lang1 = "会不会玩儿呀!你大爷的!你大爷的!你大爷的!!!";
String lang2 = lang1.replace("你大爷的", "****");
System.out.println(lang2);
}
}
[h, e, l, l, o]
[104, 101, 108, 108, 111]
会不会玩儿呀!****!****!****!!!