1.创建字符串:
String str = "hello";
String str = new String("hellow");
char[] c = {'h','e','l','l','o'};
String str = new String(c);
2.字符串比较:
String str1 = "hello";
String str2 = "hello";
System.out.print(str1 == str2);
输出结果为true;
String str1 = "hello";
String str2 = new String("hello");
System.out.print(str1 == str2)
输出结果为false;
String str1 = "hello"以这种方式创建的字符串,存放在字符串常量池中,而且一个字符串在常量池中有且只有一份。String str2 = new String(“hello”)以这种方式创建的字符串通过引用字符串常量池中的hello会在堆上生成一个str2引用的对象。也就是说str1指向的是字符串常量池中的地址,str2指向的是堆上的一个地址。二者都是引用类型所以==比较的是地址的值,所以会输出false。
3.字符串常量池:
在JVM底层实际上会自动维护一个对象池(字符串常量池):
如果现在采用了直接赋值的模式进行String类的对象实例化操作,那么该实例化对象(字符串内容)将自动保到这个对象池之中;
如果下次继续使用直接赋值的模式声明String类对象,此时对象池之中如若有指定内容,将直接进行引用;
如若没有,则开辟新的字符串对象而后将其保存在对象池之中以供下次使用;
4.字符与字符串转换:
public String (char[] value)//构造方法
String str = new String (char[] array);//用法
通过String的构造方法可以将字符数组转换为字符串。
public String (char[] value ,int offset , int count)//构造方法
String str = new String (char[] array,int index,int count)//用法
将部分字符数组中内容变为字符串。
public char charAt(int index)//普通方法
取得指定索引的字符,索引从0开始。
public char[] toCharArray()
字符串转换为数组返回
5.字节与字符串转换:
public Sting(byte bytes[])
将字节数组转换为字符串。
publi String(byte bytes[],int offset,int length)
将字节数组中部分内容转换为字符串。
public byte[] getBytes()
将字符串转换为字节数组。
public byte[] getBytes(StringcharsetName) throws UnsuppostedEncodingException
编码转换处理
6.字符串比较:
public boolean equals(Object anobject)
字符串区分大小写比较内容
public bollean equalsIgnoreCase(Object anobject)
字符串不区分大小写比较
public int compareTo(String str)
字符串大小比较,str1.comparTo(str2),如果str1大返回一个大于0的数字,如果str1小返回一个小于0的数字,相等返回0。
7.字符串查找
public boolean contains(CharSequence c)
判断子字符串c是否在串中。
public int indexOf(String str)
从头开始查找指定字符串的位置,查到了返回字符串开始的下标,否则返回-1.
public int lastIndexOf(String str)
从后开始查找指定字符串的位置,查到了返回字符串开始下标,否则返回-1.
public boolean stratsWith(String str)
判断字符串是否以指定字符串开头
public boolean endsWith(String str)
判断字符串是否以指定字符串结尾
8.字符串替换
public String replace(String str1,String str2)
将所有的str1用str2替换
public String replaceFirst(String str1,Stirng str2)
将第一个str1用str2替换。
9.字符串拆分
public String[] split(String str1)
将字符串以str1为界限,全部拆分。
public String[] split(String str1,int limit)
将字符串以str1为界限,拆分成Limit份。外有些特殊字符作为分割符可能无法正确切分, 需要加上转义。1. 字符"|","*","+“都得加上转义字符,前面加上”“2. 而如果是”",那么就得写成"\“3. 如果一个字符串中有多个分隔符,可以用”|"作为连字符。
10.字符串截取:
public String subString(int beginIndex)
从指定索引位置截取到结尾。
public String subString(int beginIndex,int endIndex)
截取某个区间的字符串,左闭右开。
11.字符串其它操作:
public String trim()
去掉字符串左右两边空格,保留中间空格
public Stirng toUpperCase()
字符串转大写。
public String toLowerCase()
字符串转小写。
public void intern()
字符串入池
public String concat(String str)
字符串连接。等同于+
public int length()
取得字符串长度
public boolean isEmpty()
判断字符串是否为空