TextUtils中能用到的方法

判断字符序列中   是否全部为数字

/**
 * Returns whether the given CharSequence contains only digits.
 */
public static boolean isDigitsOnly(CharSequence str) {
    final int len = str.length();
    for (int i = 0; i < len; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }
    return true;
}

一个分割的字符串     分隔符      分割后是否包含 item                 返回是否包含这个 item

/**
 * Does a comma-delimited list 'delimitedString' contain a certain item?
 * (without allocating memory)
 *
 * @hide
 */
public static boolean delimitedStringContains(
        String delimitedString, char delimiter, String item) {
    if (isEmpty(delimitedString) || isEmpty(item)) {
        return false;
    }
    int pos = -1;
    int length = delimitedString.length();
    while ((pos = delimitedString.indexOf(item, pos + 1)) != -1) {
        if (pos > 0 && delimitedString.charAt(pos - 1) != delimiter) {
            continue;
        }
        int expectedDelimiterPos = pos + item.length();
        if (expectedDelimiterPos == length) {
            // Match at end of string.
            return true;
        }
        if (delimitedString.charAt(expectedDelimiterPos) == delimiter) {
            return true;
        }
    }
    return false;
}


合并多个字符串

/**
 * Returns a CharSequence concatenating the specified CharSequences,
 * retaining their spans if any.
 */
public static CharSequence concat(CharSequence... text) {
    if (text.length == 0) {
        return "";
    }

    if (text.length == 1) {
        return text[0];
    }

    boolean spanned = false;
    for (int i = 0; i < text.length; i++) {
        if (text[i] instanceof Spanned) {
            spanned = true;
            break;
        }
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length; i++) {
        sb.append(text[i]);
    }

    if (!spanned) {
        return sb.toString();
    }

    SpannableString ss = new SpannableString(sb);
    int off = 0;
    for (int i = 0; i < text.length; i++) {
        int len = text[i].length();

        if (text[i] instanceof Spanned) {
            copySpansFrom((Spanned) text[i], 0, len, Object.class, ss, off);
        }

        off += len;
    }

    return new SpannedString(ss);
}

对字符串进行 html 编码

/**
 * Html-encode the string.
 * @param s the string to be encoded
 * @return the encoded string
 */
public static String htmlEncode(String s) {
    StringBuilder sb = new StringBuilder();
    char c;
    for (int i = 0; i < s.length(); i++) {
        c = s.charAt(i);
        switch (c) {
        case '<':
            sb.append("&lt;"); //$NON-NLS-1$
            break;
        case '>':
            sb.append("&gt;"); //$NON-NLS-1$
            break;
        case '&':
            sb.append("&amp;"); //$NON-NLS-1$
            break;
        case '\'':
            //http://www.w3.org/TR/xhtml1
            // The named character reference &apos; (the apostrophe, U+0027) was introduced in
            // XML 1.0 but does not appear in HTML. Authors should therefore use &#39; instead
            // of &apos; to work as expected in HTML 4 user agents.
            sb.append("&#39;"); //$NON-NLS-1$
            break;
        case '"':
            sb.append("&quot;"); //$NON-NLS-1$
            break;
        default:
            sb.append(c);
        }
    }
    return sb.toString();
}

用逗号分隔字符串

/**
 * Converts a CharSequence of the comma-separated form "Andy, Bob,
 * Charles, David" that is too wide to fit into the specified width
 * into one like "Andy, Bob, 2 more".
 *
 * @param text the text to truncate
 * @param p the Paint with which to measure the text
 * @param avail the horizontal width available for the text
 * @param oneMore the string for "1 more" in the current locale
 * @param more the string for "%d more" in the current locale
 */
public static CharSequence commaEllipsize(CharSequence text,
                                          TextPaint p, float avail,
                                          String oneMore,
                                          String more) {
    return commaEllipsize(text, p, avail, oneMore, more,
            TextDirectionHeuristics.FIRSTSTRONG_LTR);
}

截断

/**
 * Returns the original text if it fits in the specified width
 * given the properties of the specified Paint,
 * or, if it does not fit, a truncated
 * copy with ellipsis character added at the specified edge or center.
 */
public static CharSequence ellipsize(CharSequence text,
                                     TextPaint p,
                                     float avail, TruncateAt where) {
    return ellipsize(text, p, avail, where, false, null);
}

获得偏移前面的 

public static int getOffsetBefore(CharSequence text, int offset) {
    if (offset == 0)
        return 0;
    if (offset == 1)
        return 0;

    char c = text.charAt(offset - 1);

    if (c >= '\uDC00' && c <= '\uDFFF') {
        char c1 = text.charAt(offset - 2);

        if (c1 >= '\uD800' && c1 <= '\uDBFF')
            offset -= 2;
        else
            offset -= 1;
    } else {
        offset -= 1;
    }

    if (text instanceof Spanned) {
        ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
                                                   ReplacementSpan.class);

        for (int i = 0; i < spans.length; i++) {
            int start = ((Spanned) text).getSpanStart(spans[i]);
            int end = ((Spanned) text).getSpanEnd(spans[i]);

            if (start < offset && end > offset)
                offset = start;
        }
    }

    return offset;
}

偏移后面的
public static int getOffsetAfter(CharSequence text, int offset) {
    int len = text.length();

    if (offset == len)
        return len;
    if (offset == len - 1)
        return len;

    char c = text.charAt(offset);

    if (c >= '\uD800' && c <= '\uDBFF') {
        char c1 = text.charAt(offset + 1);

        if (c1 >= '\uDC00' && c1 <= '\uDFFF')
            offset += 2;
        else
            offset += 1;
    } else {
        offset += 1;
    }

    if (text instanceof Spanned) {
        ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
                                                   ReplacementSpan.class);

        for (int i = 0; i < spans.length; i++) {
            int start = ((Spanned) text).getSpanStart(spans[i]);
            int end = ((Spanned) text).getSpanEnd(spans[i]);

            if (start < offset && end > offset)
                offset = end;
        }
    }

    return offset;
}

替换

/**
 * Return a new CharSequence in which each of the source strings is
 * replaced by the corresponding element of the destinations.
 */
public static CharSequence replace(CharSequence template,
                                   String[] sources,
                                   CharSequence[] destinations) {
    SpannableStringBuilder tb = new SpannableStringBuilder(template);

    for (int i = 0; i < sources.length; i++) {
        int where = indexOf(tb, sources[i]);

        if (where >= 0)
            tb.setSpan(sources[i], where, where + sources[i].length(),
                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    for (int i = 0; i < sources.length; i++) {
        int start = tb.getSpanStart(sources[i]);
        int end = tb.getSpanEnd(sources[i]);

        if (start >= 0) {
            tb.replace(start, end, destinations[i]);
        }
    }

    return tb;
}

反转

// XXX currently this only reverses chars, not spans
public static CharSequence getReverse(CharSequence source,
                                      int start, int end) {
    return new Reverser(source, start, end);
}

相等

/**
 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check
 * @param b second CharSequence to check
 * @return true if a and b are equal
 */
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b) return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i)) return false;
            }
            return true;
        }
    }
    return false;
}

判空

/**
 * Returns true if the string is null or 0-length.
 * @param str the string to be examined
 * @return true if str is null or zero length
 */
public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0)
        return true;
    else
        return false;
}

切割

/**
 * String.split() returns [''] when the string to be split is empty. This returns []. This does
 * not remove any empty strings from the result. For example split("a,", ","  ) returns {"a", ""}.
 *
 * @param text the string to split
 * @param expression the regular expression to match
 * @return an array of strings. The array will be empty if text is empty
 *
 * @throws NullPointerException if expression or text is null
 */
public static String[] split(String text, String expression) {
    if (text.length() == 0) {
        return EMPTY_STRING_ARRAY;
    } else {
        return text.split(expression, -1);
    }
}

截取字符串

/**
 * Create a new String object containing the given range of characters
 * from the source string.  This is different than simply calling
 * {@link CharSequence#subSequence(int, int) CharSequence.subSequence}
 * in that it does not preserve any style runs in the source sequence,
 * allowing a more efficient implementation.
 */
public static String substring(CharSequence source, int start, int end) {
    if (source instanceof String)
        return ((String) source).substring(start, end);
    if (source instanceof StringBuilder)
        return ((StringBuilder) source).substring(start, end);
    if (source instanceof StringBuffer)
        return ((StringBuffer) source).substring(start, end);

    char[] temp = obtain(end - start);
    getChars(source, start, end, temp, 0);
    String ret = new String(temp, 0, end - start);
    recycle(temp);

    return ret;
}

字符串中 单个字符最后出现的角标

public static int lastIndexOf(CharSequence s, char ch) {
    return lastIndexOf(s, ch, s.length() - 1);
}





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值