String源码分析(一部分方法)

1、String不能被继承
会出现 The type TestString cannot subclass the final class String 错误。
查看源码
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
String类被final修饰,不能被继承。同时实现了几个接口。
2、
  /** The value is used for character storage. */
    private final char value [];
定义一个储存字符的变量,不过这个变量被final修饰,说明这个变量不可被改变。
3、
String str = new String();//注意,由于字符串是不可变的,所以使用此构造函数是不必要的。
4、
     /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this . value = "" . value ;
    }
除非需要显式的复制{@code original},否则使用此构造器是没有必要的,因为String字符串是不可变的。
5、String对equals方法的重写:将字符串中每个字符摘取出来比较,如果全部相等,则返回true
 
    /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

6、字符串忽略大小写的核心代码:
①、首先说一下为什么要比较完大写还要比较小写:因为在某些字母里面,例如格鲁吉亚字母表,转换大写是无效的,只能通过再次比较小写来判断。
②、最后小写比较大小:因为两个字符串长度不相同,但小写的字符相等,就会返回0。
public int compare(String s1, String s2) {
            int n1 = s1.length();
            int n2 = s2.length();
            int min = Math.min(n1, n2);
            for (int i = 0; i < min; i++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(i);
                //比较两个字符是否相等
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    //比较两个字符都变为大写后是否相等
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        //比较两个字符都变为小写后是否相等
                        //还有此处需要比较是否相等是因为若相等则直接跳出此次循环。
                        if (c1 != c2) {
                            // No overflow because of numeric promotion
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }

7、compareTo()方法的核心代码:比较相同位置字符的大小,不忽略大小写。
public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;
        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }


8、 regionMatches():匹配字符串
public boolean regionMatches ( boolean ignoreCase , int toffset ,
            String other , int ooffset , int len ) {
        char ta [] = value ;
        int to = toffset ;
        char pa [] = other . value ;
        int po = ooffset ;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if (( ooffset < 0) || ( toffset < 0)
                || ( toffset > ( long ) value . length - len )
                || ( ooffset > ( long ) other . value . length - len )) {
            return false ;
        }
        while ( len -- > 0) {
            char c1 = ta [ to ++];
            char c2 = pa [ po ++];
            if ( c1 == c2 ) {
                continue ;
            }
            if ( ignoreCase ) {
                // If characters don't match but case may be ignored,
                // try converting both characters to uppercase.
                // If the results match, then the comparison scan should
                // continue.
                char u1 = Character. toUpperCase ( c1 );
                char u2 = Character. toUpperCase ( c2 );
                if ( u1 == u2 ) {
                    continue ;
                }
                // Unfortunately, conversion to uppercase does not work properly
                // for the Georgian alphabet, which has strange rules about case
                // conversion.  So we need to make one last check before
                // exiting.
                if (Character. toLowerCase ( u1 ) == Character. toLowerCase ( u2 )) {
                    continue ;
                }
            }
            return false ;
        }
        return true ;
    }


9、 替换字符串中的某个字符
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 ;
    }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的String类是非常常用的类,它封装了字符串的常用操作,如拼接、分割、替换等。其中,replace()方法是用于替换字符串中指定字符或字符串的方法。下面我们来分析一下它的源码实现。 首先,replace()方法的参数可以是char类型或String类型,即替换的目标可以是单个字符或一段字符串。方法定义如下: ``` public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) ``` 根据方法名和参数类型可以很容易地推测出方法的作用,即在字符串中将指定字符/字符串替换成另一个字符/字符串。 接下来,我们来看一下replace()方法的具体实现,这里以方法replace(CharSequence target, CharSequence replacement)为例: ``` public String replace(CharSequence target, CharSequence replacement) { // sanity checks if (target == null) { throw new NullPointerException("target == null"); } if (replacement == null) { throw new NullPointerException("replacement == null"); } String tgtStr = target.toString(); if (tgtStr.length() == 0) { return this; } String replStr = replacement.toString(); int s = 0; int e; StringBuilder sb = null; while ((e = indexOf(tgtStr, s)) >= 0) { if (sb == null) { sb = new StringBuilder(); } sb.append(substring(s, e)).append(replStr); s = e + tgtStr.length(); } if (s == 0) { return this; } sb.append(substring(s, value.length)); return sb.toString(); } ``` 可以看到,方法内部首先进行一些参数的合法性检查,如target和replacement是否为null等。然后将CharSequence类型的target和replacement转换为String类型,以便后续操作。 接下来,使用indexOf()方法查找目标字符串在源字符串中的位置,并用substring()方法截取目标字符串前面的部分和后面的部分,然后链接上要替换成的字符串。在循环结束后,将最后一段截取的字符串链接上,最终得到替换后的结果。 总体来说,replace()方法的实现不算复杂,主要就是用上述的几个方法实现了目标替换。这也说明了Java提供的字符串处理方法非常方便实用,可以大大减少开发者的工作量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值