浅谈String类
String类
String类默认继承了Object,String表示字符串类型,属于引用数据类型,在Java中随便用双引号括起来的都是String对象。在JDK中双引号括起来的字符串都是直接存储在方法区”的字符串常量池之中,原因是字符串使用的过于频繁,为了提升效率。
1.char charAt(int index)
返回指定索引处的值(char类型)
char c = "Java".charAt(0);
System.out.println(c);//输出结果为J
2.boolean contains(CharSequence s)
判断字符串中是否包含子字符串
boolean result = "www.baidu.com".contains("baidu");
System.out.println(result);//结果为true
boolean result = "www.baidu.com".contains("baidu2");
System.out.println(result);//结果为false
3.boolean endsWith(String suffix)
判断字符串是否以某个字符串结尾
System.out.println("www.baidu.com".endsWith("com"));//结果为true
System.out.println("www.baidu.com".endsWith("com2"));//结果为false
4.boolean equalsIgnoreCase(String anotherString)
判断两个字符串是否相等,并且忽略大小写
System.out.println("JAVA".equalsIgnoreCase("java"));//结果为true
5.byte[] getBytes()
将字符串转换成字节数组
public static void main(String[] args) {
byte[] bytes = "abcdef".getBytes();
for (int i =0;i<bytes.length;i++){
System.out.println(bytes[i]);//结果为97,98,99,100,101,102
}
}
6.boolean isEmpty()
判断字符串是否为空字符串
System.out.println("java".isEmpty());//结果为false
System.out.println("".isEmpty());//结果为true
7.String replace(CharSequence target,CharSequence replacement)
将字符串中的某一部分替换
String replace = "http://www.baidu.com".replace("http","https");
System.out.println(replace); //结果为https://www.baidu.com
8.String[] split(String regex)
拆分字符串
public static void main(String[] args) {
String[] split = "2008-8-8".split("-");//将2008-8-8以-为分界线进行分割
for (int i =0;i<split.length;i++){
System.out.println(split[i]);//输出结果为2008,8,8
}
}
9.valueOf (该方法由static修饰,为静态方法)
将非字符串转换为字符串
String s = String.valueOf(true);
System.out.println(s); //结果为true
StringBuffer和StringBuilder
因为java中的字符串是不可变的,每一次的字符串拼接操作都会产生新的字符串,如果频繁的使用字符串拼接的操作,会占用大量的方法区的内存造成内存空间的浪费。如果以后需要进行大量的字符串拼接的操作,可以使用StringBuffer和StringBuilder
StringBuffer
StringBuffer的底层实际上是一个byte[]数组,往StringBuffer中放字符串,实际是放到了byte[]之中了,StringBuffer的初始化容量是16,在用stringBuffer.append进行追加的时候,如果数组满了,会调用数组拷贝的方法进行自动扩容。
StringBuilder
StringBuilder也可以进行字符串拼接,StringBuffer由synchronized关键字修饰,表示StringBuffer是线程安全的。

浙公网安备 33010602011771号