Java.String

Java.String

String 类的两种赋值方式

  • String 可以表示出一个字符串,根据String的源码我们会发现String类实际上是使用字符数组char[]存储的.

  • 如下为String的源码实现

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

    public String() {
        this.value = "".value;
    }

    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

    public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

    public String(int[] codePoints, int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= codePoints.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > codePoints.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }

        final int end = offset + count;

        // Pass 1: Compute precise size of char[]
        int n = count;
        for (int i = offset; i < end; i++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))
                continue;
            else if (Character.isValidCodePoint(c))
                n++;
            else throw new IllegalArgumentException(Integer.toString(c));
        }

        // Pass 2: Allocate and fill in char[]
        final char[] v = new char[n];

        for (int i = offset, j = 0; i < end; i++, j++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))
                v[j] = (char)c;
            else
                Character.toSurrogates(c, v, j++);
        }

        this.value = v;
    }

    public String(byte bytes[], int offset, int length, String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        checkBounds(bytes, offset, length);
        this.value = StringCoding.decode(charsetName, bytes, offset, length);
    }

    public String(byte bytes[], int offset, int length, Charset charset) {
        if (charset == null)
            throw new NullPointerException("charset");
        checkBounds(bytes, offset, length);
        this.value =  StringCoding.decode(charset, bytes, offset, length);
    }

    public String(byte bytes[], String charsetName)
            throws UnsupportedEncodingException {
        this(bytes, 0, bytes.length, charsetName);
    }

    public String(byte bytes[], Charset charset) {
        this(bytes, 0, bytes.length, charset);
    }

    public String(byte bytes[], int offset, int length) {
        checkBounds(bytes, offset, length);
        this.value = StringCoding.decode(bytes, offset, length);
    }

    public String(byte bytes[]) {
        this(bytes, 0, bytes.length);
    }

    public String(StringBuffer buffer) {
        synchronized(buffer) {
            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
        }
    }

    public String(StringBuilder builder) {
        this.value = Arrays.copyOf(builder.getValue(), builder.length());
    }
  • 常见的两种String赋值方式

    • String str1 = new String("name");
    • String str2 = "name";
  • 两种赋值方式分析

//会创建两个字符串对象,一个在常量池中创建便于下一次使用,一个在堆内存中创建
String str1 = new String("name");
//最多创建一个字符串对象,有可能不用创建对象(如果常量池中已经存在相应的常量)
String str2 = "name";//推荐使用

内存分析
[图片上传失败...(image-c5ddcb-1539494239877)]

String类编译期与运行期分析

  • 首先明确对象之间 "==" 是比较两个对象的地址。
public class StringDemo {
    
    public static void main(String[] args) {
        
        // 情况一   结果为true
        String aString = "a1";
        String a1String = "a" + 1;
        System.out.println(aString == a1String);
        
        
        // 情况二    结果为false
        String bString = "b1";
        int bb = 1;
        String b1String = "b" + bb;
        System.out.println(bString == b1String);
        
        
        // 情况三    结果为true
        String cString = "c1";
        final int cc = 1;
        String c1String = "c" + cc;
        System.out.println(cString == c1String);
    
    
        // 情况四     结果为false
        String dString = "dd";
        final int dd = getDD();
        String d1String = dString + dd;
        System.out.println(dString == d1String);
        
    }
    
    public static int getDD(){
        return 1;
    }
}
  • 情况二为false,因为 b1String 在编译期时是还没有完全确定下来的,因为 bb 是一个变量,只有在执行期才能加载到。
  • 情况四为false,注意与情况三进行对比,虽然使用了final关键字,但是根据函数返回值确定下来的,而函数要执行仍然是在运行期的时候确定的,编译期仍然无法确定。

String 类字符与字符串操作方法

  • 字符与字符串操作

[图片上传失败...(image-eca866-1539494239877)]

  • 字节与字符串操作

[图片上传失败...(image-56d4c7-1539494239878)]

  • 是否以指定内容开头或结尾

[图片上传失败...(image-2dff3e-1539494239878)])

  • String 类替换操作

[图片上传失败...(image-3eeda5-1539494239878)]

  • String 类字符串截取操作

[图片上传失败...(image-c062a1-1539494239878)]

  • 字符串拆分操作

[图片上传失败...(image-a70b6e-1539494239878)]

  • String 类字符串查找操作

[图片上传失败...(image-21d210-1539494239878)]

  • String 类其他操作方法

[图片上传失败...(image-ae04d2-1539494239878)]

  • 更多请见相关api文档

  • 常见用例

System.out.println("abcde".charAt(3));//d
System.out.println("abcde".toCharArray()[2]);//c
byte[] bytes = "abcde".getBytes();
for(int i = 0; i < bytes.length; i++){
    System.out.println(bytes[i]);
}
System.out.println(new String(bytes).toString());
System.out.println(new String(bytes,0,2).toString());//ab
System.out.println(new String(bytes,"utf-8").toString());

System.out.println("abcde".startsWith("ab"));//true
System.out.println("abcde".startsWith("cd",2));//true
System.out.println("abcde".endsWith("de"));//true

System.out.println("abc,de".replace(",", ":").toString());//abc:de
System.out.println("abcde".replace("ab", "AB"));//ABcde
        
//匹配正则表达式中26个字母替换为相应的字符串
System.out.println("abcde".replaceAll("[a-z]", "*"));//*****
System.out.println("abcde".replaceFirst("[a-z]", "*"));//*bcde

//包括起始位置
System.out.println("abcde".substring(2));//cde
//包括起始位置,不包括结束位置
System.out.println("abcde".substring(1, 3));//bc 

String[] value = "ab-cde".split("-");//传入的参数为正则表达式
String[] value2 = "ab-c-de".split("-",3);//拆分成三个字符串数组
for(String s:value){
    System.out.print(s);
}
System.out.println();
for(String s:value2){
    System.out.print(s);
}

System.out.println("abcde".contains("abc"));//true
System.out.println("abcde".indexOf("a"));//0  参数虽然为整形,但会转为unicode字符
System.out.println("abcde".indexOf("bc"));//0 返回首地址
System.out.println("abcded".lastIndexOf("d"));//5
System.out.println("abcdede".lastIndexOf("de"));//5

System.out.println("abcde".isEmpty());//false
System.out.println("abcde".length());//5
System.out.println("abcde".toUpperCase());//ABCDE
System.out.println("ABCDE".toLowerCase());//abcde
System.out.println(" abcde ".trim());//abcde
System.out.println("abc".concat("de"));//abcde
  • 源码
    public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }
    
    public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }
    
    // 使用平台默认的编码转换成字节数组,默认gbk,根据虚拟机
    public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    }
    
    public String(byte bytes[]) {
        this(bytes, 0, bytes.length);
    }
    
    public String(byte bytes[], int offset, int length) {
        checkBounds(bytes, offset, length);
        this.value = StringCoding.decode(bytes, offset, length);
    }
    
    public String(byte bytes[], String charsetName)
            throws UnsupportedEncodingException {
        this(bytes, 0, bytes.length, charsetName);
    }
    
    public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);
    }
    
    public boolean startsWith(String prefix, int toffset) {
        char ta[] = value;//调用该方法的对象的value
        int to = toffset;//偏移量
        char pa[] = prefix.value;//前缀的value
        int po = 0;//前缀的偏移量
        int pc = prefix.value.length;//前缀的总数
        // Note: toffset might be near -1>>>1.
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;
        }
        while (--pc >= 0) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }
    
    public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }
    
    
    public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            while (++i < len) {
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                while (i < len) {
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }
    
    public String replaceFirst(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
    }
    
    public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    }
    
    public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }
    
    public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }
    
    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }
    
    public String[] split(String regex, int limit) {
        /* fastpath if the regex is a
         (1)one-char String and this character is not one of the
            RegEx's meta characters ".$|()[{^?*+\\", or
         (2)two-char String and the first char is the backslash and
            the second is not the ascii digit or ascii letter.
         */
        char ch = 0;
        if (((regex.value.length == 1 &&
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
             (regex.length() == 2 &&
              regex.charAt(0) == '\\' &&
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
              ((ch-'a')|('z'-ch)) < 0 &&
              ((ch-'A')|('Z'-ch)) < 0)) &&
            (ch < Character.MIN_HIGH_SURROGATE ||
             ch > Character.MAX_LOW_SURROGATE))
        {
            int off = 0;
            int next = 0;
            boolean limited = limit > 0;
            ArrayList<String> list = new ArrayList<>();
            while ((next = indexOf(ch, off)) != -1) {
                if (!limited || list.size() < limit - 1) {
                    list.add(substring(off, next));
                    off = next + 1;
                } else {    // last one
                    //assert (list.size() == limit - 1);
                    list.add(substring(off, value.length));
                    off = value.length;
                    break;
                }
            }
            // If no match was found, return this
            if (off == 0)
                return new String[]{this};

            // Add remaining segment
            if (!limited || list.size() < limit)
                list.add(substring(off, value.length));

            // Construct result
            int resultSize = list.size();
            if (limit == 0) {
                while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
                    resultSize--;
                }
            }
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }
    
    public String[] split(String regex) {
        return split(regex, 0);
    }
    
    public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }
    
    public int indexOf(String str) {
        return indexOf(str, 0);
    }
    
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }
    
    public int indexOf(int ch) {
        return indexOf(ch, 0);
    }
    
    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }
    
    public int lastIndexOf(int ch, int fromIndex) {
        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            int i = Math.min(fromIndex, value.length - 1);
            for (; i >= 0; i--) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return lastIndexOfSupplementary(ch, fromIndex);
        }
    }
    
    public int lastIndexOf(int ch) {
        return lastIndexOf(ch, value.length - 1);
    }
    
    public boolean isEmpty() {
        return value.length == 0;
    }
    
    public int length() {
        return value.length;
    }
    
    public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }
    
    public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容

  • 前言 String 是Java语言非常基础和重要的类,提供了构造和管理字符串的各种基本逻辑。它是典型的 Immut...
    _Zy阅读 732评论 0 3
  • 我们经常会面对一个问题,String 是最基本的数据类型吗?String 是值类型还是引用类型? 首先我们来回答第...
    Tim在路上阅读 906评论 0 6
  • 1.String 字符串 字符串广泛应用 在Java 编程中,在 Java 中字符串属于对象,Java 提供了 S...
    TESTME阅读 303评论 0 0
  • 什么是生活之美?居住自由主义?选择追从内心?丰富的精神世界?还是可以触摸到的真实质感?所有的方式似乎都需要一件好物...
    mars小德子阅读 654评论 0 1
  • 作为家长,当您的孩子早恋,或者偷了您的钱,又或者沉迷游戏,您如何教导?用言语说服?还是用棍棒解决? 作为老师,当您...
    Kara欢阅读 289评论 0 2