【JAVA SE】24.String

来源:互联网 发布:作弊神器软件下载 编辑:程序博客网 时间:2024/06/02 04:26

一、String类(java.lang.String)

String s1 = "abc"; //s1是类类型变量,"abc"是一个对象String s2 = new String("abc"); //有两个对象("abc"new出的)String s3 = "abc";System.out.println(s1 == s2); //falseSystem.out.println(s1.equals(s2)); //trueSystem.out.println(s1 == s3); //true//s1,s3指向同一个对象。因为"abc"第一句执行时已经存在,再指向这个字符串时,就不再新建,指向已存在的那个对象,节省内存。
  • “…”为该类的一个对象
  • 不变性:String 对象创建后则不能被修改,所谓的修改其实是创建了新的对象,所指向的内存空间不同。
  • 给同一变量赋不同字符串,两个字符串是两个对象,地址不同。
  • == 和equals() 区别
    • ==: 判断两个字符串在内存中地址是否相同,即判断是否是同一个字符串对象
    • equals(): 比较存储在两个字符串对象中的内容是否一致(String类覆写了equals()方法)
  • 空串和null串区别:
    • 空串“”是长度为0的字符串,是一个对象
    • null串,表示目前没有任何对象与该变量关联

二、String类常用方法(查阅API文档)

这里写图片描述

  • 获取
    • 获取字符串长度:public int length()
    • 返回给定位置的代码单元:public char charAt(int index),除非对底层代码单元感兴趣,否则不需要调用这个方法。
    • 根据字符获取该字符在字符串中的位置:
      int indexOf(int ch)
      int indexOf(int ch, int fromIndex)
      int indexOf(String str)
      int indexOf(String str, int fromIndex)
      返回字符串str或代码点ch第一次出现的位置,位置从索引0或fromIndex开始计算,如果在原始串中不存在str/ch,返回-1。
      int lastIndexOf(int ch)
      int lastIndexOf(int ch, int fromIndex)
      int lastIndexOf(String str)
      int lastIndexOf(String str, int fromIndex)
      反向索引,从尾部或者fromIndex开始计算,返回字符串str或代码点ch第一次出现的位置,如果在原始串中不存在str/ch,返回-1。
public class Text {    public static void main(String[] args){        String s = "abcaefacae";        sop(s.length());        sop(s.charAt(3));        sop(s.indexOf('a'));//        sop(s.indexOf('a',1));        sop(s.indexOf("cae"));        sop(s.indexOf("cae",4));        sop(s.lastIndexOf('a'));    }       public static void sop(Object obj) {        System.out.println(obj);    }}
  • 判断
    • 字符串中是否包含某一指定子串str:boolean contains(String str)也可以使用indexOf(String str)判断是否包含:if(str.indexOf("abc") != -1)str字符串包含”abc”,该方法即可以判断,又可以获取出现的位置
    • 字符串是否有内容(判断长度是否为0):boolean isEmpty()
    • 字符串是否以prefix开头,是则返回true:boolean startsWith(String prefix)
    • 字符串是否以suffix结尾,是则返回true:boolean endsWith(String suffix)
    • 判断字符串内容是否与other相同,是则返回true(覆写了Object中的该方法):boolean equals(String other)
    • 判断字符串内容是否与other相同(忽略大小写),是则返回true:boolean equalsIgnoreCase(String other)
public class Text {    public static void main(String[] args){        String s = "abcDemo.java";        String s1 = "abcDemo.JAVA";        sop(s.contains("Demo"));        sop(s.isEmpty());        sop(s.startsWith("abc"));        sop(s.endsWith(".java"));        sop(s.equals(s1));        sop(s.equalsIgnoreCase(s1));    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:truefalsetruetruefalsetrue
  • 转换
    • 将字符数组转成字符串:
      • 构造方法:
        String(char[] value)
        String(char[] value, int offset, int count)将字符数组中的一部分转为字符串,offset是起始位置(包含),count是从起始位置开始要转换的个数
      • 静态方法:
        static String copyValueOf(char[] data)
        static String copyValueOf(char[] data, int offset, int count)
        static String valueOf(int a),将基本数据类型转成字符串
    • 将字符串转成字符数组:char[] toCharArray()
    • 将字节数组转成字符串:
      String(byte[] bytes)原理同上
      String(byte[] bytes, int offset, int length)
    • 将字符串转成字节数组:byte[] getBytes()
    • 将基本数据类型转成字符串(一般不用):
static String valueOf(char c)static String valueOf(double d)...//可以使用3+"";形式//字符串和字节数组在转换过程中是可以指定编码表的
public class Text {    public static void main(String[] args){        char[] a = {'a','b','c','D','e','m','o'};        String str = "abc";        String s = new String(a);        String s1 = new String(a, 1, 3);        String s3 = String.copyValueOf(a);        String s4 = String.valueOf(a);        String s5 = String.copyValueOf(a, 1, 3);        char[] c = str.toCharArray();        sop(s);        sop(s1);        sop(s3);        sop(s4);        sop(s5);        for(int i = 0; i < c.length; i++) {            sop(c[i]);        }    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:abcDemobcDabcDemoabcDemobcDabc
  • 替换
String replace(CharSequence oldString, CharSequence newString)//字符串替换,CharSequence是接口,String是其子类
public class Text {    public static void main(String[] args){        String str = "abc";        String str1 = str.replace('a','w');        String str2 = str.replace("abc","abcdef");        sop(str);        sop(str1);        sop(str2);    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:abcwbcabcdef
  • 切割:Strign[] split(String regex)
public class Text {    public static void main(String[] args){        String str = "abc,def";        String str2 = "abcmmdefmmghi";        String[] str1 = str.split(",");        String[] str3 = str2.split("mm");        for(int i = 0; i<str1.length; i++) {            sop(str1[i]);        }        for(int i = 0; i<str3.length; i++) {            sop(str3[i]);        }    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:abcdefabcdefghi
  • 子串
    String substring(int beginIndex)获取从beginIndex开始到结尾,包含头的子串
    String substring(int beginIndex, int endIndex)获取从beginIndex开始到endIndex结尾,包头不包尾的子串
public class Text {    public static void main(String[] args){        String str = "abcdef";        sop(str.substring(2));        sop(str.substring(2,4));    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:cdefcd
  • 转换、去除空格、比较
    • 转换:将原始字符串中的字母转成大写或小写
      String toUpperCase()
      String toLowerCase()
    • 删除原始字符串两端多余的空格,返回一个新字符串:String trim()
    • 对字符串按照字典顺序进行比较:int compareTo(String other)
      如果相等,返回0;如果字符串位于other之前,返回负数;如果字符串位于other之后,返回一个正数(ascii值比较,返回差值)
public class Text {    public static void main(String[] args){        String str = "abcdef";        String str1 = "ABCDEF";        String str2 = "   abc def   ";        sop(str.toUpperCase());        sop(str1.toLowerCase());        sop(str2.trim());        sop(str.compareTo(str1));    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:ABCDEFabcdefabc def32
  • 用给定定界符连接多个元素,返回一个新的字符串:String join(CharSequence delimiter,CharSequence... elements)
public class Text {    public static void main(String[] args) {        String s = String.join("/", "S", "L", "M");        sopl(s);    }}//运行结果:S/L/M

二、StringBuffer(构建器)

  • StringBuffer:相当于盒子,向盒子中装各种东西或者拿出,盒子还是那个盒子不变,内容可变。

    • 可操作多个数据类型
    • 允许采用多线程的方式执行添加或删除字符的操作,其效率有些低。

    这里写图片描述

  • 存储:
    • StringBuffer append(String str):将指定str作为参数添加到已有元素的结尾处
    • StringBuffer insert(int offset, String str):将str插入到offset指定位置
public class Text {    public static void main(String[] args){        StringBuffer str = new StringBuffer();        //StringBuffer str1 = str.append(1);        str.append(1).append(2).append(3);        sop(str);        //sop(str1);        //sop(str == str1);//str,str1同一个对象        str.insert(1, 0);        sop(str);           }       public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:1231023
  • 删除:
    • StringBuffer delete(int start, int end)删除从start到end-1之间的元素
    • StringBuffer deleteCharAt(int index)删除指定位置index处的字符
public class Text {    public static void main(String[] args){        StringBuffer str = new StringBuffer("abcde");        str.delete(1, 3);//bc        sop(str);        str.deleteCharAt(0);//a        sop(str);        str.delete(0, str.length());//清空缓冲区         }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:adede
  • 获取
    • char charAt(index)
    • String substring(int start, int end)
  • 修改
    • StringBuffer replace(int start, int end, String str)包头不包尾+要替换的字符串
    • void setCharAt(int i, char c)将i位置的字符替换成c
  • 反转
    • StringBuffer reverse ()
public class Text {    public static void main(String[] args){        StringBuffer str = new StringBuffer("abcde");        str.replace(1, 3, "12");//bc        sop(str);        str.setCharAt(0, '0');        sop(str);        str.reverse();        sop(str);    }    public static void sop(Object obj) {        System.out.println(obj);    }}//运行结果:a12de012deed210
  • String toString():返回一个与构建器或缓冲区内容相同的字符串
public class Text {    public static void main(String[] args) {        StringBuffer s = new StringBuffer();        s.append("123");        s.append("123");        String str = s.toString();        sopl(str);    }}//运行结果:123123

三、StringBuilder

  • 单线程(字符串通常在一个单线程),所以性能略高,JDK 1.5版本后出现。
  • 开发,应优先考虑使用 StringBuilder 类。
  • 方法和StringBuffer类中方法相同
1 0
原创粉丝点击