1 String类概述
字符串是由多个字符组成的一串数据(字符序列)的字符串常量,j
ava中所有字符串都是String类的实例.
2创建方式
2.1 方式一
String s = "abc";
先在栈中创建一个对String类的对象引用变量s,然后去字符串常量池中查找有没有"abc", 如果没有则在常量池中添加”abc”, s引用变量指向常量池中的”abc”,如果常量池中有,则直接指向改地址即可,不用重新创建。
2.2方式二
在堆中创建新对象,值存储在堆内存的对象中。
String s = new String("abc");
3构造方法
3.1直接创建法
public String()
//括号内直接用双引号引用所需要赋的值
String s1=new String("ABC");
3.2将一个byte数组转化为一个字符串
public String(byte[] bytes)
String s1=new String("ABC");
byte []bytes=s1.getBytes();
String s2= new String(bytes);
System.out.println(s2);
运行结果为
ABC
3.3将char数组转化为一个字符串
public String(char[] value)
4判断方法
4.1判断两个字符串内容是否相等
equals(Object obj)
Java String类中已经重写了equals方法,其功能是判断两个字符串内容是否相等。如果相等则返回true,否则返回false。
String s1=new String("ABC");
byte []bytes=s1.getBytes();
String s2= new String(bytes);
System.out.println(s1.equals(s2));
运行结果为
true
4.2 判断两个字符串是否相等,不区分大小写;
equalsIgnoreCase() 方法的作用和语法与 equals() 方法完全相同,唯一不同的是equalsIgnoreCase() 比较时不区分大小写。当比较两个字符串时,它会认为 A-Z 和 a-z 是一样的。如果是则返回true,否则返回false。
String s1=new String("ABC");
String s2=new String("abc");
System.out.println(s1.equalsIgnoreCase(s2));
运行结果为
true
4.3 判断一个字符串中是否含有另一个字符串
contains(String str)
如果是则返回true,否则返回false。
String s1=new String("abcdef");
String s2=new String("abc");
System.out.println(s1.contains(s2));
运行结果
true
4.4 判断一个字符串是否为空
isEmpty()
如果是则返回true,否则返回false。
String s1=new String("abcdef");
String s2=new String("");
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
运行结果
false
true
4.5判断一个字符串是否以指定字符串开始
startsWith(String prefix)
String s1="abcdefg";
String s2="abc";
String s3="abb";
System.out.println(s1.startsWith(s2));
System.out.println(s1.startsWith(s3));
运行结果为
true
false
4.6 判断一个字符串是否以指定字符串结束
endsWith(String suffix)
String s1="abcdefg";
String s2="efg";
String s3="abb";
System.out.println(s1.endsWith(s2));
System.out.println(s1.endsWith(s3));
运行结果为
true
false
5. 获取方法
5.1获取字符串长度
length(),返回值为int类型,即为字符串的长度。
String s1="abcdefg";
String s2="efg";
String s3="abbasdads";
System.out.println(s1.length());
System.out.println(s2.length());
System.out.println(s3.length());
运行结果为
7
3
9
5.2 获取字符串指定索引的内容
charAt(int index)
String s1="abcdefg";
String s2="efg";
String s3="abbasdads";
System.out.println(s1.charAt(3));
System.out.println(s2.charAt(2));
System.out.println(s3.charAt(6));
运行结果为
d
g
a
5.3查找一个字符串中是否含有另一个字符串
indexOf(String str,int fromIndex)
从指定位置开始查找,返回指定字符在原字符串中的第一个匹配项的索引。若省略第二个参数,则从头开始查找。如果没有则返回负值。若指定字符为字符串则则返回第一个字符的索引。
String s1="abcdefg";
String s2="efg";
String s3="abbasdads";
System.out.println(s1.indexOf("d"));
System.out.println(s3.indexOf("f"));
运行结果为
3
-1
5.4截取字符串的指定位置
substring(int start,int end),从start开始截取到end位置结束(不包含end位置),如果省略第二个参数,则截取到最后一位。
String s1="abcdefg";
String s2="efg";
String s3="abbasdads";
System.out.println(s1.substring(3, 4));
System.out.println(s3.substring(4));
运行结果
d
sdads
6. 转换功能
6.1将字符串通过默认编码转换为byte数组
String a="abcxcba";
byte[] bytes=a.getBytes();
for (int i = 0; i < bytes.length-1; i++) {
System.out.println(bytes[i]);
}
运行结果
97
98
99
120
99
98