Administrator
发布于 2023-07-13 / 50 阅读
0
0

String Best Practise

字符串截取

字符串截取,目前有2种方式:StringBuilder 、substring

StringBuilder#append


    /**
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    @Override
    public StringBuilder append(char[] str, int offset, int len) {
        super.append(str, offset, len);
        return this;
    }
    

    /**
     * Appends the string representation of a subarray of the
     * {@code char} array argument to this sequence.
     * <p>
     * Characters of the {@code char} array {@code str}, starting at
     * index {@code offset}, are appended, in order, to the contents
     * of this sequence. The length of this sequence increases
     * by the value of {@code len}.
     * <p>
     * The overall effect is exactly as if the arguments were converted
     * to a string by the method {@link String#valueOf(char[],int,int)},
     * and the characters of that string were then
     * {@link #append(String) appended} to this character sequence.
     *
     * @param   str      the characters to be appended.
     * @param   offset   the index of the first {@code char} to append.
     * @param   len      the number of {@code char}s to append.
     * @return  a reference to this object.
     * @throws IndexOutOfBoundsException
     *         if {@code offset < 0} or {@code len < 0}
     *         or {@code offset+len > str.length}
     */
    public AbstractStringBuilder append(char str[], int offset, int len) {
        if (len > 0)                // let arraycopy report AIOOBE for len < 0
            ensureCapacityInternal(count + len);
        System.arraycopy(str, offset, value, count, len);
        count += len;
        return this;
    }

示例:

public static void main(String[] args) {
        String address = "江苏省南京市雨花台区";

        String province = "省";
        String city = "市";

        char[] src = address.toCharArray();

        int provinceStart = 0;
        int provinceEnd = address.indexOf(province);


        StringBuilder provinceBuilder = new StringBuilder();
        provinceBuilder.append(src,provinceStart,provinceEnd-provinceStart+1);  // 截取的范围 [start 总共截取len个chars

        System.out.println(provinceBuilder.toString()); // 江苏省

        //
        StringBuilder cityBuilder = new StringBuilder();
        int cityStart = provinceEnd+1;
        int cityEnd = address.indexOf(city);
        cityBuilder.append(src,cityStart,cityEnd-cityStart+1);
        System.out.println(cityBuilder.toString()); // 南京市
    }

String#substring


/**
     * 加密密码前缀
     */
    public static final String ENCRYPT_PASSWD_PREFIX = "encrypt";
    
rawPassword = rawPassword.substring(rawPassword.indexOf(Constants.ENCRYPT_PASSWD_PREFIX) + Constants.ENCRYPT_PASSWD_PREFIX.length());

评论