栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java面试题--String中的属性和常用方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java面试题--String中的属性和常用方法

本文章学习参考的文章:

https://www.cnblogs.com/duanxz/p/3511695.html

https://blog.csdn.net/weixin_44365021/article/details/85775813

https://blog.csdn.net/windy8833/article/details/5292481


String中的属性
   
   // 这里的这个value常量就是String不可变的原因,因为用了final修饰
    private final char value[];// 这个是jdk1.8的底层,使用了char,而在1.9底层变成了byte

    
    private int hash; // 默认值是0
    
    
    private static final long serialVersionUID = -6849794470754667710L;

String中的常用方法
	public String() {
	        this.value = "".value;
	    }

默认生成一个空的字符串


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

当构造函数中传递一个值的时候,value就是值,hash就是值的hash


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

Arrays.copyOf的返回值是一个新的char[],第一个参数是值,第二个参数是新数组的长度


 public int length() {
        return value.length;
    }

返回int类型,获取字符串的长度


    public boolean isEmpty() {
        return value.length == 0;
    }

判断字符串是否为空


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

获取指定下标处的char的具体值,下标从0开始


    public int codePointAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointAtImpl(value, index, value.length);
    }

获取对应索引下的char 的code值


    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

应用:

        String str = "123456";
        char[] chars = {'a', 'b', 'c'};

        str.getChars(1, 3, chars, 1);

        for (char aChar : chars) {
            System.out.print(aChar);
        }

运行结果:

由此可以看出,这个方法的作用是从str的1索引开始到3,复制覆盖到chars的从第1个索引位置开始
索引从0开始


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

将字符串转换成byte数组,(“1” 的byte是49)


    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;
    }

java在String的底层重写了equals方法,比较的是两个字符串的值value是否相同,而如果是自定义的类的话,没有重写equals会比较两个对象的地址。


这里我创建了两个不同的对象在堆内存中,通过 两个不同的引用来指向这两个字符串,两个的地址是不同的但是值相同,equals返回的是true,由此可以看出比较的是两个的值。


    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;
    }

继承了Comparable接口,重写了里面的compareTo方法,用来比较排序
返回为正数表示a1>a2, 返回为负数表示a1


  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;
    }

获取这个字符串对象的hashcode值


    public int indexOf(int ch) {
        return indexOf(ch, 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);
        }
    }

默认从第0索引开始,判断字符串中有没有byte为ch的字符,没有就返回-1,有则返回这个字符的索引位置。这个方法也可以直接传入一个字符串或者字符,也可以查询出来。


   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);
    }

将两个字符串首尾连接起来,返回一个新的String对象


    public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; 

            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;
    }

将字符串的存在的子串进行替换,换成新的字符串,然后返回一个新的String对象。


    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }

判断字符串中是否存在相应的子串,boolean


    public String toLowerCase() {
        return toLowerCase(Locale.getDefault());
    }
 public String toLowerCase(Locale locale) {
        if (locale == null) {
            throw new NullPointerException();
        }

        int firstUpper;
        final int len = value.length;

        
        scan: {
            for (firstUpper = 0 ; firstUpper < len; ) {
                char c = value[firstUpper];
                if ((c >= Character.MIN_HIGH_SURROGATE)
                        && (c <= Character.MAX_HIGH_SURROGATE)) {
                    int supplChar = codePointAt(firstUpper);
                    if (supplChar != Character.toLowerCase(supplChar)) {
                        break scan;
                    }
                    firstUpper += Character.charCount(supplChar);
                } else {
                    if (c != Character.toLowerCase(c)) {
                        break scan;
                    }
                    firstUpper++;
                }
            }
            return this;
        }

        char[] result = new char[len];
        int resultOffset = 0;  

        
        System.arraycopy(value, 0, result, 0, firstUpper);

        String lang = locale.getLanguage();
        boolean localeDependent =
                (lang == "tr" || lang == "az" || lang == "lt");
        char[] lowerCharArray;
        int lowerChar;
        int srcChar;
        int srcCount;
        for (int i = firstUpper; i < len; i += srcCount) {
            srcChar = (int)value[i];
            if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
                    && (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
                srcChar = codePointAt(i);
                srcCount = Character.charCount(srcChar);
            } else {
                srcCount = 1;
            }
            if (localeDependent ||
                srcChar == 'u03A3' || // GREEK CAPITAL LETTER SIGMA
                srcChar == 'u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE
                lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
            } else {
                lowerChar = Character.toLowerCase(srcChar);
            }
            if ((lowerChar == Character.ERROR)
                    || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
                if (lowerChar == Character.ERROR) {
                    lowerCharArray =
                            ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
                } else if (srcCount == 2) {
                    resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
                    continue;
                } else {
                    lowerCharArray = Character.toChars(lowerChar);
                }

                
                int mapLen = lowerCharArray.length;
                if (mapLen > srcCount) {
                    char[] result2 = new char[result.length + mapLen - srcCount];
                    System.arraycopy(result, 0, result2, 0, i + resultOffset);
                    result = result2;
                }
                for (int x = 0; x < mapLen; ++x) {
                    result[i + resultOffset + x] = lowerCharArray[x];
                }
                resultOffset += (mapLen - srcCount);
            } else {
                result[i + resultOffset] = (char)lowerChar;
            }
        }
        return new String(result, 0, len + resultOffset);
    }

将字符串中大写的字符变成小写


    public String toUpperCase() {
        return toUpperCase(Locale.getDefault());
    }

将字符串中小写的字符变成大写


  public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

除去String中的空格


    public String toString() {
        return this;
    }

返回字符串的值,如果对象是null会抛出异常NullPointerException


    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;
    }

将字符串转化成char数组


    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

返回字符串的值,如果对象是null不会抛出异常,会返回null


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322487.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号