登录 立即注册
安币:

一个安卓开发中常用的字符串工具类 [复制链接]

2018-11-7 10:21
sergiochanTest 阅读:268 评论:0 赞:1
Tag:  

一个安卓开发中常用的字符串工具类分享。

public class StringUtils {

    private StringUtils() {
        throw new AssertionError();
    }

    /**
     * 密码
     *
     * @param pwd
     * @return
     */
    public static boolean isPwd(String pwd) {
        int length = pwd.length();
        boolean falg = false;
        if (length >= 6 &amp;&amp; length <= 16) {
            falg = true;
        } else {
            falg = false;
        }
        return falg;
    }

    /**
     * 纯数字
     *
     * @param str
     * @return
     */

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 纯字母
     *
     * @param
     * @return
     */
    public static boolean isChar(String data) {
        boolean flag = false;
        for (int i = data.length(); --i >= 0; ) {
            char c = data.charAt(i);
            if (((c >= 'a' &amp;&amp; c <= 'z') || (c >= 'A' &amp;&amp; c <= 'Z'))) {
                flag = true;
            } else {
                flag = false;
            }
        }

        return flag;
    }

    /*数字+字母*/
    public static boolean ispsd(String psd) {
        Pattern p = Pattern
                .compile("^([A-Za-z]|[0-9])+$");
        Matcher m = p.matcher(psd);

        return m.matches();
    }

    /**
     * 手机验证
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(14[57])|(17[0])|(17[7])|(18[0,0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);

        return m.matches();
    }

    /**
     * 验证邮政编码
     *
     * @param post
     * @return
     */
    public static boolean checkPost(String post) {
        if (post.matches("[1-9]\\d{5}(?!\\d)")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 计算金额
     *
     * @param argStr
     * @return
     */
    public static String getFloatDotStr(String argStr) {
        float arg = Float.valueOf(argStr);
        DecimalFormat fnum = new DecimalFormat("##0.00");
        return fnum.format(arg);
    }

    /**
     * is null or its length is 0 or it is made by space
     * <p/>
     * <pre>
     * isBlank(null) = true;
     * isBlank(&amp;quot;&amp;quot;) = true;
     * isBlank(&amp;quot;  &amp;quot;) = true;
     * isBlank(&amp;quot;a&amp;quot;) = false;
     * isBlank(&amp;quot;a &amp;quot;) = false;
     * isBlank(&amp;quot; a&amp;quot;) = false;
     * isBlank(&amp;quot;a b&amp;quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0 or it is made by space, return
     * true, else return false.
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * is null or its length is 0
     * <p/>
     * <pre>
     * isEmpty(null) = true;
     * isEmpty(&amp;quot;&amp;quot;) = true;
     * isEmpty(&amp;quot;  &amp;quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0, return true, else return
     * false.
     */
    public static boolean isEmpty(CharSequence str) {
        return (str == null || str.length() == 0);
    }

    /**
     * get length of CharSequence
     * <p/>
     * <pre>
     * length(null) = 0;
     * length(\"\") = 0;
     * length(\"abc\") = 3;
     * </pre>
     *
     * @param str
     * @return if str is null or empty, return 0, else return
     * {@link CharSequence#length()}.
     */
    public static int length(CharSequence str) {
        return str == null ? 0 : str.length();
    }

    /**
     * null Object to empty string
     * <p/>
     * <pre>
     * nullStrToEmpty(null) = &amp;quot;&amp;quot;;
     * nullStrToEmpty(&amp;quot;&amp;quot;) = &amp;quot;&amp;quot;;
     * nullStrToEmpty(&amp;quot;aa&amp;quot;) = &amp;quot;aa&amp;quot;;
     * </pre>
     *
     * @param str
     * @return
     */
    public static String nullStrToEmpty(Object str) {
        return (str == null ? "" : (str instanceof String ? (String) str : str
                .toString()));
    }

    /**
     * capitalize first letter
     * <p/>
     * <pre>
     * capitalizeFirstLetter(null)     =   null;
     * capitalizeFirstLetter("")       =   "";
     * capitalizeFirstLetter("2ab")    =   "2ab"
     * capitalizeFirstLetter("a")      =   "A"
     * capitalizeFirstLetter("ab")     =   "Ab"
     * capitalizeFirstLetter("Abc")    =   "Abc"
     * </pre>
     *
     * @param str
     * @return
     */
    public static String capitalizeFirstLetter(String str) {
        if (isEmpty(str)) {
            return str;
        }

        char c = str.charAt(0);
        return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str
                : new StringBuilder(str.length())
                .append(Character.toUpperCase(c))
                .append(str.substring(1)).toString();
    }

    /**
     * encoded in utf-8
     * <p/>
     * <pre>
     * utf8Encode(null)        =   null
     * utf8Encode("")          =   "";
     * utf8Encode("aa")        =   "aa";
     * utf8Encode("啊啊啊啊")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
     * </pre>
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException if an error occurs
     */
    public static String utf8Encode(String str) {
        if (!isEmpty(str) &amp;&amp; str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(
                        "UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }

    /**
     * encoded in utf-8, if exception, return defultReturn
     *
     * @param str
     * @param defultReturn
     * @return
     */
    public static String utf8Encode(String str, String defultReturn) {
        if (!isEmpty(str) &amp;&amp; str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return defultReturn;
            }
        }
        return str;
    }

    /**
     * get innerHtml from href
     * <p/>
     * <pre>
     * getHrefInnerHtml(null)                                  = ""
     * getHrefInnerHtml("")                                    = ""
     * getHrefInnerHtml("mp3")                                 = "mp3";
     * getHrefInnerHtml("&amp;lt;a innerHtml&amp;lt;/a&amp;gt;")                    = "&amp;lt;a innerHtml&amp;lt;/a&amp;gt;";
     * getHrefInnerHtml("&amp;lt;a&amp;gt;innerHtml&amp;lt;/a&amp;gt;")                    = "innerHtml";
     * getHrefInnerHtml("&amp;lt;a&amp;lt;a&amp;gt;innerHtml&amp;lt;/a&amp;gt;")                    = "innerHtml";
     * getHrefInnerHtml("&amp;lt;a href="baidu.com"&amp;gt;innerHtml&amp;lt;/a&amp;gt;")               = "innerHtml";
     * getHrefInnerHtml("&amp;lt;a href="baidu.com" title="baidu"&amp;gt;innerHtml&amp;lt;/a&amp;gt;") = "innerHtml";
     * getHrefInnerHtml("   &amp;lt;a&amp;gt;innerHtml&amp;lt;/a&amp;gt;  ")                           = "innerHtml";
     * getHrefInnerHtml("&amp;lt;a&amp;gt;innerHtml&amp;lt;/a&amp;gt;&amp;lt;/a&amp;gt;")                      = "innerHtml";
     * getHrefInnerHtml("jack&amp;lt;a&amp;gt;innerHtml&amp;lt;/a&amp;gt;&amp;lt;/a&amp;gt;")                  = "innerHtml";
     * getHrefInnerHtml("&amp;lt;a&amp;gt;innerHtml1&amp;lt;/a&amp;gt;&amp;lt;a&amp;gt;innerHtml2&amp;lt;/a&amp;gt;")        = "innerHtml2";
     * </pre>
     *
     * @param href
     * @return <ul>
     * <li>if href is null, return ""</li>
     * <li>if not match regx, return source</li>
     * <li>return the last string that match regx</li>
     * </ul>
     */
    public static String getHrefInnerHtml(String href) {
        if (isEmpty(href)) {
            return "";
        }

        String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
        Pattern hrefPattern = Pattern
                .compile(hrefReg, Pattern.CASE_INSENSITIVE);
        Matcher hrefMatcher = hrefPattern.matcher(href);
        if (hrefMatcher.matches()) {
            return hrefMatcher.group(1);
        }
        return href;
    }

    /**
     * process special char in html
     * <p/>
     * <pre>
     * htmlEscapeCharsToString(null) = null;
     * htmlEscapeCharsToString("") = "";
     * htmlEscapeCharsToString("mp3") = "mp3";
     * htmlEscapeCharsToString("mp3&amp;lt;") = "mp3<";
     * htmlEscapeCharsToString("mp3&amp;gt;") = "mp3\>";
     * htmlEscapeCharsToString("mp3&amp;amp;mp4") = "mp3&amp;mp4";
     * htmlEscapeCharsToString("mp3&amp;quot;mp4") = "mp3\"mp4";
     * htmlEscapeCharsToString("mp3&amp;lt;&amp;gt;&amp;amp;&amp;quot;mp4") = "mp3\<\>&amp;\"mp4";
     * </pre>
     *
     * @param source
     * @return
     */
    public static String htmlEscapeCharsToString(String source) {
        return StringUtils.isEmpty(source) ? source : source
                .replaceAll("&amp;lt;", "<").replaceAll("&amp;gt;", ">")
                .replaceAll("&amp;amp;", "&amp;").replaceAll("&amp;quot;", "\"");
    }

    /**
     * transform half width char to full width char
     * <p/>
     * <pre>
     * fullWidthToHalfWidth(null) = null;
     * fullWidthToHalfWidth("") = "";
     * fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
     * fullWidthToHalfWidth("!"#$%&) = "!\"#$%&amp;";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String fullWidthToHalfWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == 12288) {
                source[i] = ' ';
                // } else if (source[i] == 12290) {
                // source[i] = '.';
            } else if (source[i] >= 65281 &amp;&amp; source[i] <= 65374) {
                source[i] = (char) (source[i] - 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * transform full width char to half width char
     * <p/>
     * <pre>
     * halfWidthToFullWidth(null) = null;
     * halfWidthToFullWidth("") = "";
     * halfWidthToFullWidth(" ") = new String(new char[] {12288});
     * halfWidthToFullWidth("!\"#$%&amp;) = "!"#$%&";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String halfWidthToFullWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == ' ') {
                source[i] = (char) 12288;
                // } else if (source[i] == '.') {
                // source[i] = (char)12290;
            } else if (source[i] >= 33 &amp;&amp; source[i] <= 126) {
                source[i] = (char) (source[i] + 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * 删除String最后一个字符
     *
     * @param text
     * @return
     */
    public static String trimLast(String text) {
        String result = "";
        result = text.substring(0, text.length() - 1);
        return result;
    }

    public static String noZero(int number) {
        if (number == 0) {
            return "";
        } else {
            return String.valueOf(number);
        }
    }

    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String srt = s.toString();

                if (srt.contains(".")) {

                    String rex = "[0-9]{0,9}\\.{1}[0-9]{0,2}";
                    Pattern pattern = Pattern.compile(rex);
                    if (pattern.matches(rex, srt)) {
                        if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                            s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                            editText.setText(s);
                            editText.setSelection(s.length());
                        }
                        String strs[] = srt.split("\\.");
                        if (strs != null &amp;&amp; strs.length > 0) {

                            if (strs[0].length() > 8) {

                                String newStr = strs[0].substring(0, strs[0].length() - 1);
                                editText.setText(newStr + "." + strs[1]);
                                editText.setSelection(newStr.length());
                            }
                            System.out.println("strs==" + strs.length);
                        }
                    } else {

                        if (srt.length() != 0) {
                            if (srt.length() == editText.getSelectionEnd()) {
                                srt = srt.substring(0, srt.length() - 1);
                                editText.setText(srt);
                                editText.setSelection(srt.length());
                            } else {

                                srt = srt.substring(0, editText.getSelectionEnd() - 1);
                                editText.setText(srt);
                                editText.setSelection(srt.length());
                            }

                        }

                    }

                } else {
                    if (srt.length() > 8) {
                        if (srt.length() != 0) {
                            srt = srt.substring(0, srt.length() - 1);
                            editText.setText(srt);
                            editText.setSelection(srt.length());
                        }
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0") &amp;&amp; s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }
}

大家自己看一下吧 基本都有注释,并不难理解,如果哪块我有写的不对的地方也可以给我指出来,大家一起进步~

分享到:
我来说两句
facelist
您需要登录后才可以评论 登录 | 立即注册
所有评论(0)

站长推荐

通过邮件订阅最新安卓weekly信息
上一条 /4 下一条

下载安卓巴士客户端

全国最大的安卓开发者社区

广告投放| 下载客户端|申请友链|手机版|站点统计|安卓巴士 ( 粤ICP备15117877号 )

返回顶部