美文网首页
String类的相关知识

String类的相关知识

作者: Swen_9826 | 来源:发表于2018-11-22 21:10 被阅读22次
    当你发现时光是贼了,它早已经偷光了你的所有选择!
    • public final class String
    • extends Object
    • implements Serializable, Comparable<String>, CharSequence

    API中描述:

    • The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

    • Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

    中文翻译为:

    • String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。
    • 字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享

    String类的成员变量:

        /** String的属性值 */  
        private final char value[];
    
        /** The offset is the first index of the storage that is used. */
        /**数组被使用的开始位置**/
        private final int offset;
    
        /** The count is the number of characters in the String. */
        /**String中元素的个数**/
        private final int count;
    
        /** Cache the hash code for the string */
       /**String类型的hash值**/
        private int hash; // Default to 0
    
        /** use serialVersionUID from JDK 1.0.2 for interoperability */
        private static final long serialVersionUID = -6849794470754667710L;
        /**
         * Class String is special cased within the Serialization Stream      Protocol.
         *
         * A String instance is written into an ObjectOutputStream according to
         * <a href="{@docRoot}/../platform/serialization/spec/output.html">
         * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
         */
    
      private static final ObjectStreamField[] serialPersistentFields =
            new ObjectStreamField[0];
    

    String的每个成员变量是被final修饰的,是不可以被改变的,因此String的值只要有改变就会生成一个新的String类型对象。

    String类的构造方法:

    String() 
    //初始化一个新创建的 String 对象,使其表示一个空字符序列。 
    
    String(byte[] bytes) 
    //通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。 
    
    String(byte[] bytes, Charset charset) 
    //通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。 
     
    String(byte[] bytes, int offset, int length) 
    //通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。 
    
    String(byte[] bytes, int offset, int length, Charset charset) 
    //通过使用指定的 charset 解码指定的 byte 子数组,构造一个新的 String。 
    
    String(byte[] bytes, int offset, int length, String charsetName) 
    //通过使用指定的字符集解码指定的 byte 子数组,构造一个新的 String。 
    
    String(byte[] bytes, String charsetName) 
    //通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。 
    
    String(char[] value) 
    //分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。 
    
    String(char[] value, int offset, int count) 
    //分配一个新的 String,它包含取自字符数组参数一个子数组的字符。 
    
    String(int[] codePoints, int offset, int count) 
    //分配一个新的 String,它包含 Unicode 代码点数组参数一个子数组的字符。 
    
    String(String original) 
    //初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列;
    //换句话说,新创建的字符串是该参数字符串的副本。 
    
    String(StringBuffer buffer) 
    //分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。 
    
    String(StringBuilder builder) 
    //分配一个新的字符串,它包含字符串生成器参数中当前包含的字符序列。
    

    构造方法测试:

        public static void main(String[] args) {
            //方法一:String();
            String s1=new String();
            //String这个类重写了Object父类的方法,return this;
            System.out.println("s1:"+s1);
            System.out.println("s1.length:"+s1.length());
            System.out.println("*********************");
      
            //方法二:String(byte[] bytes)
            byte[] byts={97,98,99,100,101,102};
            String s2=new String(byts);
            System.out.println("s2:"+s2);
            System.out.println("s2.length:"+s2.length());
            System.out.println("*********************");
            
            //方法三:String (byte[] bytes,int index,int length)
            byte[] byts2={97,98,99,100,101,102};
            String s3=new String(byts2,2,4);
            System.out.println("s3:"+s3);
            System.out.println("s3.length:"+s3.length());
            System.out.println("*********************");
            
            //方法四:String(char[] value)
            char [] value={'a','b','c','d','e','f'};
            String s4=new String(value);
            System.out.println("s4:"+s4);
            System.out.println("s4.length:"+s4.length());
            System.out.println("*********************");
            
            //方法五:String(char[] value,int index,int length)
            char [] value2={'a','b','c','d','e','f'};
            String s5=new String(value,2,4);
            System.out.println("s5:"+s5);
            System.out.println("s5.length:"+s5.length());
            System.out.println("*********************");
            
            //方法六:String(String str)
            String s6=new String("abcdef");
            System.out.println("s6:"+s6);
            System.out.println("s6.length:"+s6.length());
            System.out.println("*********************");
            
        }
    

    测试结果:

    s1:
    s1.length:0
    *********************
    s2:abcdef
    s2.length:6
    *********************
    s3:cdef
    s3.length:4
    *********************
    s4:abcdef
    s4.length:6
    *********************
    s5:cdef
    s5.length:4
    *********************
    s6:abcdef
    s6.length:6
    *********************
    

    字符串实例化方法与区别:

    • 方法一
      String str="Hello Swen ";//直接赋值的方式
    • 方法二
      String str=new String("Hello Swen ");//实例化的方式
    • 两种方法区别

    对于方法一来说,采用直接赋值的方式(String str="Hello Swen ")进行对象的实例化,则会将匿名对象“Hello Swen”放入对象池,每当下一次对不同的对象进行直接赋值的时候会直接利用池中原有的匿名对象,这样,所有直接赋值的String对象相等,返回true;

    对于方法二来说,第一次实例化时在堆中分配内存,如图:


    第一次new

    在第二次new相同字符串时会在堆内存中重新分配内存,创建对象,见图:


    第二次new
    • 总结:直接赋值只开辟一块堆内存空间,并且会自动入池,不会产生垃圾。构造方法会开辟两块堆内存空间,其中一块堆内存会变成垃圾被系统回收,而且不能够自动入池,需要通过public String intern();方法进行手工入池。在开发的过程中不会采用构造方法进行字符串的实例化

    String类常用方法:

    • public int length()
      返回该字符串的长度
            String str = "Hello Swen";      
            System.out.println("字符串的长度:"+str.length());
            //字符串的长度:10
    
    • public char charAt(int index)
      返回字符串中指定位置的字符;注意字符串中第一个字符索引是0,最后一个是length()-1
            String str = "Hello Swen";  
            System.out.println("指定位置的字符:"+str.charAt(0));
            //指定位置的字符:H
    
    • public String substring(int beginIndex)
      该方法从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回
      public String substring(int beginIndex, int endIndex)
      该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回
            String str = "Hello Swen";
            System.out.println("提取字符串中的子串:"+str.substring(6));
            //提取字符串中的子串:Swen
            System.out.println("提取字符串中的子串:"+str.substring(6,10));
            //提取字符串中的子串:Swen
    
    • public boolean equalsIgnoreCase(String anotherString)
      与equals方法相似,但忽略大小写
      public boolean equals(Object anotherObject)
      比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false
      public int compareToIgnore(String anotherString)
      与compareTo方法相似,但忽略大小写
      public int compareTo(String anotherString)
      该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0
            String str = "Hello Swen";
            System.out.println("字符串比较:"+str.equals("Hello Swen"));
            //字符串比较:true
            System.out.println("字符串比较:"+str.equalsIgnoreCase("hello swen"));
            //字符串比较:true
            System.out.println("字符串比较:"+str.compareTo("Hallo Swen"));
            //字符串比较:4
            System.out.println("字符串比较:"+str.compareToIgnoreCase("hello swem"));
            //字符串比较:1
    
    • public String concat(String str)
      将参数中的字符串str连接到当前字符串的后面,效果等价于"+"
            String str = "Hello Swen";
            System.out.println("字符串连接:"+str.concat("--记得加油哦!"));
            //字符串连接:Hello Swen--记得加油哦!
    
    • public int indexOf(int ch/String str)
      用于查找当前字符串中字符或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1
      public int indexOf(int ch/String str, int fromIndex)
      改方法与第一种类似,区别在于该方法从fromIndex位置向后查找
      public int lastIndexOf(int ch/String str)
      该方法与第一种类似,区别在于该方法从字符串的末尾位置向前查找
      public int lastIndexOf(int ch/String str, int fromIndex)
      该方法与第二种方法类似,区别于该方法从fromIndex位置向前查找
            String str = "Hello Swen";
            System.out.println("字符串中单个字符查找:"+str.indexOf('l'));
            //字符串中单个字符查找:2
            System.out.println("字符串中单个字符查找:"+str.indexOf("Swen"));
            //字符串中单个字符查找:6
            System.out.println("字符串中单个字符查找:"+str.indexOf('l',3));
            //字符串中单个字符查找:3
            System.out.println("字符串中单个字符查找:"+str.lastIndexOf("l"));
            //字符串中单个字符查找:3
            System.out.println("字符串中单个字符查找:"+str.lastIndexOf("wen"));
            //字符串中单个字符查找:7
    
    • public String toLowerCase()
      返回将当前字符串中所有字符转换成小写后的新串
      public String toUpperCase()
      返回将当前字符串中所有字符转换成大写后的新串
            String str = "Hello Swen";
            System.out.println("字符串中字符的大小写转换:"+str.toUpperCase());
            //字符串中字符的大小写转换:HELLO SWEN
            System.out.println("字符串中字符的大小写转换:"+str.toLowerCase());
            //字符串中字符的大小写转换:hello swen
    
    • public String replace(char oldChar, char newChar)
      用字符newChar替换当前字符串中所有的oldChar字符,并返回一个新的字符串
      public String replaceFirst(String regex, String replacement)
      该方法用字符replacement的内容替换当前字符串中遇到的第一个和字符串regex相匹配的子串,应将新的字符串返回
      public String replaceAll(String regex, String replacement)
      该方法用字符replacement的内容替换当前字符串中遇到的所有和字符串regex相匹配的子串,应将新的字符串返回
            String str = "Hello Swen";
            System.out.println("字符串中字符的替换:"+str.replace('l', 'a'));
            //字符串中字符的替换:Heaao Swen
            System.out.println("字符串中字符的替换:"+str.replace("l", "oo"));
            //字符串中字符的替换:Heooooo Swen
            System.out.println("字符串中字符的替换:"+str.replaceFirst("He", "xxx"));
            //字符串中字符的替换:xxxllo Swen
            System.out.println("字符串中字符的替换:"+str.replaceAll("l", "qq"));
            //字符串中字符的替换:Heqqqqo Swen
    
    • String trim()
      截去字符串两端的空格,但对于中间的空格不处理
            String str = "Hello Swen ";
            System.out.println("去掉空格前:"+str.length());
            System.out.println("去掉空格后:"+str.trim().length());
            //去掉空格前:11
            //去掉空格后:10
    
    • contains(String str)
      判断参数s是否被包含在字符串中,并返回一个布尔类型的值
            String str = "Hello Swen";
            System.out.println("包含:"+str.contains("Swen"));
            //包含:true
    
    • String[] split(String str)
      将str作为分隔符进行字符串分解,分解后的字字符串在字符串数组中返回
            String str = "Hello Swen";
            System.out.println("分割:"+str.split(" ")[0]+"----"+str.split(" ")[1]);
            //分割:Hello----Swen
    
    • static String valueOf(char data[])
      static String valueOf(char data[], int offset, int count)
      static String valueOf(boolean b)
      static String valueOf(char c)
      static String valueOf(int i)
      static String valueOf(long l)
      static String valueOf(float f)
      static String valueOf(double d)
      基本类型转换为字符串类型
      String类中提供了String valueOf()放法,用作基本类型转换为字符串类型
            System.out.println(String.valueOf(12.23).length());
            //5
    
    • public static byte parseByte(String s)
      public static short parseShort(String s)
      public static short parseInt(String s)
      public static long parseLong(String s)
      public static float parseFloat(String s)
      public static double parseDouble(String s)
      字符串转换为基本类型
      java.lang包中有Byte、Short、Integer、Float、Double类的调用方法
            String s = "236";
            System.out.println(Integer.parseInt(s) == 236);
            //true
    

    相关文章

      网友评论

          本文标题:String类的相关知识

          本文链接:https://www.haomeiwen.com/subject/rsulqqtx.html