从源码分析String类中的常用方法

0.构造方法

字符串的构造方法有多种,可以通过String、byte、char、int、StringBuffer 、StringBuilder 等数据类型构造,部分构造方法如下:

  • String():初始化新创建的 String对象,使其表示空字符序列。
public String() {
        this.value = "".value;
    }
  • String(String original):初始化新创建的String对象,使其表示与参数相同的字符序列。
public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
  • String(byte[] bytes):通过使用平台的默认字符集解码指定的字节数组来构造新的 String 。
public String(byte bytes[]) {
        this(bytes, 0, bytes.length);
    }
复制代码
  • String(byte[] bytes, Charset charset):构造一个新的String由指定用指定的字节的数组解码charset 。
public String(byte bytes[], Charset charset) {
        this(bytes, 0, bytes.length, charset);
    }
复制代码
  • String(char value[]):分配一个新的 String ,以便它表示当前包含在字符数组参数中的字符序列。
public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }
复制代码
  • String(StringBuffer buffer):分配一个新的字符串,其中包含当前包含在buffer参数中的字符序列。
public String(StringBuffer buffer) {
        synchronized(buffer) {
            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
        }
    }
复制代码
  • String(StringBuilder builder):分配一个新的字符串,其中包含当前包含在builder参数中的字符序列。
public String(StringBuilder builder) {
        this.value = Arrays.copyOf(builder.getValue(), builder.length());
    }
复制代码

1.char charAt(int index)

返回字符串中指定索引index处的字符。

public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }
复制代码

其中value的定义如下:

/** The value is used for character storage. */
    private final char value[];
复制代码

String类的一个构造方法为:

public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
复制代码

可见,String在底层实际上是由一个用final关键字修饰的不可变的字符数组存储的。 String.charAt(index)就是返回value[index]。

2.int compareTo(String anotherString)

逐个字符比较两个字符串,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至不等为止,返回该字符的ASCII码差值。 如果两个字符串不一样长,可对应字符又完全一样,则返回两个字符串的长度差值。

		 * @param   anotherString   the {@code String} to be compared.
     * @return  the value {@code 0} if the argument string is equal to
     *          this string; a value less than {@code 0} if this string
     *          is lexicographically less than the string argument; and a
     *          value greater than {@code 0} if this string is
     *          lexicographically greater than the string argument.
     */
    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;	//同位置的字符不相等,返回该字符的ASCII码差值
            }
            k++;
        }
        return len1 - len2;		//两个字符串不一样长,可对应字符又完全一样,则返回两个字符串的长度差值
    }
复制代码

3.String concat(String str)

将指定的字符串拼接到该字符串的末尾。

*
     * @param   str   the {@code String} that is concatenated to the end
     *                of this {@code String}.
     * @return  a string that represents the concatenation of this object's
     *          characters followed by the string argument's characters.
     */
    public String concat(String str) {
        if (str.isEmpty()) {
            return this;
        }
        int len = value.length;
        int otherLen = str.length();
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }
复制代码

4.boolean contains(CharSequence s)

当且仅当此字符串中包含指定的CharSequence 时才返回true。

*
     * @param s the sequence to search for
     * @return true if this string contains {@code s}, false otherwise
     * @since 1.5
     */
    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }
复制代码

其中CharSequence是一个描述字符串结构的接口,像String、StringBuilder、StringBuffer都是它的子接口。

5.boolean startsWith(String prefix, int toffset)

测试在指定索引处开始的此字符串的子字符串是否以指定的前缀开头。 toffset为指定开始索引

public boolean startsWith(String prefix, int toffset) {
        char ta[] = value;
        int to = toffset;
        char pa[] = prefix.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;
    }
复制代码

6.boolean endsWith(String suffix)

测试此字符串是否以指定的后缀结尾。

public boolean endsWith(String suffix) {
				//调用startsWith方法,相当从value.length - suffix.value.length索引处比较
        return startsWith(suffix, value.length - suffix.value.length);
    }
复制代码

7.boolean equals(Object anObject)

将此字符串与指定对象进行比较。

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;
    }
复制代码

8.String format(String format, Object... args)

使用指定的格式字符串和参数返回格式化的字符串。

9.byte[] getBytes()

使用平台的默认字符集将此 String编码为字节序列,将结果存储到新的字节数组中。

public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }
复制代码

10.int hashCode()

返回此字符串的哈希码。

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
复制代码

11.int indexOf(int ch)

返回指定字符第一次出现的字符串内的索引。

12.int lastIndexOf(int ch)

返回指定字符的最后一次出现的字符串中的索引。

13.boolean isEmpty()

当且仅当length()为0时返回true。

public boolean isEmpty() {
        return value.length == 0;
    }
复制代码

14.int length()

返回此字符串的长度。

public int length() {
        return value.length;
    }
复制代码

15.boolean matches(String regex)

告诉这个字符串是否匹配给定的 regular expression (正则表达式)。

public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }
复制代码

16.String replaceAll(String regex, String replacement)

用给定的字符串替换与给定的 regular expression匹配此字符串的每个子字符串。

17.String replaceFirst(String regex, String replacement)

用给定的字符串替换与给定的 regular expression匹配此字符串的第一个子字符串。

18.String[] split(String regex)

将此字符串分割为给定的 regular expression的匹配。返回分割后的字符串数组。

public String[] split(String regex) {
        return split(regex, 0);
    }
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).isEmpty()) {
                    resultSize--;
                }
            }
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }
复制代码

19.String substring(int beginIndex, int endIndex)

返回一个字符串,该字符串(索引beginIndex到endIndex之间的字符串)是此字符串的子字符串。

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);
    }
复制代码

20.char[] toCharArray()

将此字符串转换为新的字符数组。

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;
    }
复制代码

21.String toLowerCase()

将此字符串中的字符全部小写。

22.String toUpperCase()

将此字符串中的字符全部大写。

23.String trim()

删除字符串的头尾空白符(中间空白符将保留)。

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;
    }
复制代码

24. String valueOf()

将传入参数转换为字符串。

  • String.valueOf(boolean b) : 将 boolean 变量 b 转换成字符串
  • String.valueOf(char c) : 将 char 变量 c 转换成字符串
  • String.valueOf(char[] data) : 将 char 数组 data 转换成字符串
  • String.valueOf(char[] data, int offset, int count) :

将 char 数组 data 中 由 data[offset] 开始取 count 个元素 转换成字符串

  • String.valueOf(double d) : 将 double 变量 d 转换成字符串
  • String.valueOf(float f) : 将 float 变量 f 转换成字符串
  • String.valueOf(int i) : 将 int 变量 i 转换成字符串
  • String.valueOf(long l) : 将 long 变量 l 转换成字符串
  • String.valueOf(Object obj) : 将 obj 对象转换成 字符串
public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
    
public static String valueOf(char data[]) {
        return new String(data);
    }
    
public static String valueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    }
    
public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }
    
public static String valueOf(char c) {
        char data[] = {c};
        return new String(data, true);
    }
    
public static String valueOf(int i) {
        return Integer.toString(i);
    }
    
public static String valueOf(long l) {
        return Long.toString(l);
    }
    
public static String valueOf(float f) {
        return Float.toString(f);
    }
    
public static String valueOf(double d) {
        return Double.toString(d);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值