常用Stirng相关操作类

这个工具类提供了多种字符串处理方法,包括检查是否同时含有字母和数字、字符串变色、搜索关键词高亮、MD5加密、XML和HTML颜色设置等。此外,还包含了手机号、邮箱、数字和字母验证,以及字符串数组的处理。
摘要由CSDN通过智能技术生成
//判断字符串中是否同时含有数字及字母 
public static boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值,用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值,用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        boolean isRight = isDigit && isLetter;
        return isRight;

    }

给字符串变色的2种方法

 /**
     * xml 方式
     *
     * @param con   原字符串
     * @param key   需要变色的文案
     * @param color 颜色色值
     * @return
     *   使用textview.setText(Html.escapeHtml(getStringXML()))
     */
    public static String getStringXML(String con, String key, String color) {
        return con.replace(key, "<font color= '" + color + "'>" + key + "</font>");

    }

    /**
     * 给填写搜索单词的关键词显示 特殊颜色
     *
     * @param word  原文案
     * @param input 关键字
     * @param color  颜色
     * @param context  context
     * @return
     */
    public static SpannableStringBuilder changeTextColor(String word, String input, int color, Context context) {
        int len = input.length();
        int start = 0;
        int end = 0;
        int position = 0;
        SpannableStringBuilder style = new SpannableStringBuilder(word);
        while (true) {
            position = word.indexOf(input, end);
            if (-1 == position) {
                break;
            }
            start = position;
            end = start + len;
            style.setSpan(new ForegroundColorSpan(context.getResources().getColor(color)), start, end,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return style;
    }

粘贴太麻烦了 直接整个工具类粘这


/**
 * 名称:StringUtil.java
 * 描述:字符串处理类.
 */
public class StringUtil {

    public static String getStringxx(double d) {
        return Double.valueOf(String.format("%.2f", d)).toString();
    }

    //判断密码是否符合规则
    public static boolean passwordIsLegal(String password) {
        if (TextUtils.isEmpty(password) || password.length() < 6 || password.length() > 20)
            return false;
        else
            return isLetterDigit(password);
    }

    public static boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值,用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值,用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        boolean isRight = isDigit && isLetter;
        return isRight;

    }


    public static boolean ispsd(String psd) {
        Pattern p = Pattern

                .compile("^[a-zA-Z].*[0-9]|.*[0-9].*[a-zA-Z]");

        Matcher m = p.matcher(psd);

        return m.matches();

    }

    public static ArrayList<String> getStringArray(String str) {
        return new ArrayList<>(Arrays.asList(geturl(str)));

    }

    public static ArrayList<String> getStringArrayd(String str) {
        return new ArrayList<>(Arrays.asList(getStrs(str)));

    }


    public static String getMD5Str(String str) {
        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest = md5.digest(str.getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        String md5Str = new BigInteger(1, digest).toString(16);
        return md5Str;
    }

    /**
     * xml 方式
     *
     * @param con   原字符串
     * @param key   需要变色的文案
     * @param color 颜色色值
     * @return
     */
    public static String getStringXML(String con, String key, String color) {
        return con.replace(key, "<font color= '" + color + "'>" + key + "</font>");

    }

    /**
     * 给填写搜索单词的关键词显示 特殊颜色
     *
     * @param word  原文案
     * @param input 关键字
     * @param color  颜色
     * @param context  context
     * @return
     */
    public static SpannableStringBuilder changeTextColor(String word, String input, int color, Context context) {
        int len = input.length();
        int start = 0;
        int end = 0;
        int position = 0;
        SpannableStringBuilder style = new SpannableStringBuilder(word);
        while (true) {
            position = word.indexOf(input, end);
            if (-1 == position) {
                break;
            }
            start = position;
            end = start + len;
            style.setSpan(new ForegroundColorSpan(context.getResources().getColor(color)), start, end,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return style;
    }

    public static String[] geturl(String item) {
        if (StringUtil.isEmpty(item))
            return new String[]{};
        String[] temp = item.split(";");
//        for (int i = 0; i < temp.length; i++) {
//            temp[i] = ApiHost.getImageUrl(temp[i]);
//        }
        return temp;
    }

    public static String[] getStrs(String item) {
        if (StringUtil.isEmpty(item))
            return new String[]{};
        String[] temp = item.split(",");
//        for (int i = 0; i < temp.length; i++) {
//            temp[i] = ApiHost.getImageUrl(temp[i]);
//        }
        return temp;
    }

    /**
     * 描述:将null转化为“”.
     *
     * @param str 指定的字符串
     * @return 字符串的String类型
     */
    public static String parseEmpty(String str) {
        if (str == null || "null".equals(str.trim())) {
            str = "";
        }
        return str.trim();
    }

    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmpty(String str) {
        return str == null || str == "" || str.trim().length() == 0 || str.equals("null");
    }

    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmptys(String... str) {
        for (int i = 0; i < str.length; i++) {
            if (isEmpty(str[i])) {
                return true;
            }
        }
        return false;
    }


    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmpty(String str, String tost) {
        boolean isEmpty = str == null || str.trim().length() == 0 || str.equals("null");
        if (isEmpty)
            ToastUtils.showMessage(tost);
        return isEmpty;
    }

    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmpty(TextView str, String tost) {

        boolean isEmpty = str == null || str.getText().toString().trim().length() == 0 || str.equals("null");
        if (isEmpty)
            ToastUtils.showMessage(tost);
        return isEmpty;
    }

    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmpty(TextView str) {

        boolean isEmpty = str == null || str.getText().toString().trim().length() == 0 || str.equals("null");
        return isEmpty;
    }


    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmpty(List str, String tost) {

        boolean isEmpty = isEmpty(str);
        if (isEmpty)
            ToastUtils.showMessage(tost);
        return isEmpty;
    }

    /**
     * 集合是否为空
     *
     * @param list
     * @return
     */
    public static boolean isEmpty(List list) {
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }

    /**
     * 获取字符串中文字符的长度(每个中文算2个字符).
     *
     * @param str 指定的字符串
     * @return 中文字符的长度
     */
    public static int chineseLength(String str) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
        if (!isEmpty(str)) {
            for (int i = 0; i < str.length(); i++) {
                /* 获取一个字符 */
                String temp = str.substring(i, i + 1);
                /* 判断是否为中文字符 */
                if (temp.matches(chinese)) {
                    valueLength += 2;
                }
            }
        }
        return valueLength;
    }

    /**
     * 描述:获取字符串的长度.
     *
     * @param str 指定的字符串
     * @return 字符串的长度(中文字符计2个)
     */
    public static int strLength(String str) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        if (!isEmpty(str)) {
            //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
            for (int i = 0; i < str.length(); i++) {
                //获取一个字符
                String temp = str.substring(i, i + 1);
                //判断是否为中文字符
                if (temp.matches(chinese)) {
                    //中文字符长度为2
                    valueLength += 2;
                } else {
                    //其他字符长度为1
                    valueLength += 1;
                }
            }
        }
        return valueLength;
    }

    /**
     * 描述:获取指定长度的字符所在位置.
     *
     * @param str  指定的字符串
     * @param maxL 要取到的长度(字符长度,中文字符计2个)
     * @return 字符的所在位置
     */
    public static int subStringLength(String str, int maxL) {
        int currentIndex = 0;
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
        for (int i = 0; i < str.length(); i++) {
            //获取一个字符
            String temp = str.substring(i, i + 1);
            //判断是否为中文字符
            if (temp.matches(chinese)) {
                //中文字符长度为2
                valueLength += 2;
            } else {
                //其他字符长度为1
                valueLength += 1;
            }
            if (valueLength >= maxL) {
                currentIndex = i;
                break;
            }
        }
        return currentIndex;
    }

    /**
     * 描述:手机号格式验证.
     *
     * @param str 指定的手机号码字符串
     * @return 是否为手机号码格式:是为true,否则false
     */
    public static Boolean isMobileNo(String str) {
        Boolean isMobileNo = false;
        try {
            Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(18[0-9])|(14[0-9])|(17[0-9]))\\d{8}$");
            Matcher m = p.matcher(str);
            isMobileNo = m.matches();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isMobileNo;
    }

    /**
     * 描述:是否只是字母和数字.
     *
     * @param str 指定的字符串
     * @return 是否只是字母和数字:是为true,否则false
     */
    public static Boolean isNumberLetter(String str) {
        Boolean isNoLetter = false;
        String expr = "^[A-Za-z0-9]+$";
        if (str.matches(expr)) {
            isNoLetter = true;
        }
        return isNoLetter;
    }

    /**
     * 描述:是否只是数字.
     *
     * @param str 指定的字符串
     * @return 是否只是数字:是为true,否则false
     */
    public static Boolean isNumber(String str) {
        Boolean isNumber = false;
        String expr = "^[0-9]+$";
        if (str.matches(expr)) {
            isNumber = true;
        }
        return isNumber;
    }

    /**
     * 描述:是否是邮箱.
     *
     * @param str 指定的字符串
     * @return 是否是邮箱:是为true,否则false
     */
    public static Boolean isEmail(String str) {
        Boolean isEmail = false;
        String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        if (str.matches(expr)) {
            isEmail = true;
        }
        return isEmail;
    }

    /**
     * 描述:是否是中文.
     *
     * @param str 指定的字符串
     * @return 是否是中文:是为true,否则false
     */
    public static Boolean isChinese(String str) {
        Boolean isChinese = true;
        String chinese = "[\u0391-\uFFE5]";
        if (!isEmpty(str)) {
            //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
            for (int i = 0; i < str.length(); i++) {
                //获取一个字符
                String temp = str.substring(i, i + 1);
                //判断是否为中文字符
                if (temp.matches(chinese)) {
                } else {
                    isChinese = false;
                }
            }
        }
        return isChinese;
    }

    /**
     * 描述:是否包含中文.
     *
     * @param str 指定的字符串
     * @return 是否包含中文:是为true,否则false
     */
    public static Boolean isContainChinese(String str) {
        Boolean isChinese = false;
        String chinese = "[\u0391-\uFFE5]";
        if (!isEmpty(str)) {
            //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
            for (int i = 0; i < str.length(); i++) {
                //获取一个字符
                String temp = str.substring(i, i + 1);
                //判断是否为中文字符
                if (temp.matches(chinese)) {
                    isChinese = true;
                } else {

                }
            }
        }
        return isChinese;
    }

    /**
     * 是否包含中文数字字母的用户名
     * 长度1-20
     *
     * @param str
     * @return
     */
    public static boolean isConintChinseUser(String str) {
        /**此正则表达式将上面二者结合起来进行判断,中文、大小写字母和数字**/
        String all = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w]{2,10}$";
        Pattern pattern = Pattern.compile(all);
        return pattern.matcher(str).matches();
    }

    /**
     * 描述:从输入流中获得String.
     *
     * @param is 输入流
     * @return 获得的String
     */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            //最后一个\n删除
            if (sb.indexOf("\n") != -1 && sb.lastIndexOf("\n") == sb.length() - 1) {
                sb.delete(sb.lastIndexOf("\n"), sb.lastIndexOf("\n") + 1);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 描述:标准化日期时间类型的数据,不足两位的补0.
     *
     * @param dateTime 预格式的时间字符串,如:2012-3-2 12:2:20
     * @return String 格式化好的时间字符串,如:2012-03-20 12:02:20
     */
    public static String dateTimeFormat(String dateTime) {
        StringBuilder sb = new StringBuilder();
        try {
            if (isEmpty(dateTime)) {
                return null;
            }
            String[] dateAndTime = dateTime.split(" ");
            if (dateAndTime.length > 0) {
                for (String str : dateAndTime) {
                    if (str.indexOf("-") != -1) {
                        String[] date = str.split("-");
                        for (int i = 0; i < date.length; i++) {
                            String str1 = date[i];
                            sb.append(strFormat2(str1));
                            if (i < date.length - 1) {
                                sb.append("-");
                            }
                        }
                    } else if (str.indexOf(":") != -1) {
                        sb.append(" ");
                        String[] date = str.split(":");
                        for (int i = 0; i < date.length; i++) {
                            String str1 = date[i];
                            sb.append(strFormat2(str1));
                            if (i < date.length - 1) {
                                sb.append(":");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sb.toString();
    }

    /**
     * 描述:不足2个字符的在前面补“0”.
     *
     * @param str 指定的字符串
     * @return 至少2个字符的字符串
     */
    public static String strFormat2(String str) {
        try {
            if (str.length() <= 1) {
                str = "0" + str;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 描述:截取字符串到指定字节长度.
     *
     * @param str    the str
     * @param length 指定字节长度
     * @return 截取后的字符串
     */
    public static String cutString(String str, int length) {
        return cutString(str, length, "");
    }

    /**
     * 描述:截取字符串到指定字节长度.
     *
     * @param str    文本
     * @param length 字节长度
     * @param dot    省略符号
     * @return 截取后的字符串
     */
    public static String cutString(String str, int length, String dot) {
        int strBLen = strlen(str, "GBK");
        if (strBLen <= length) {
            return str;
        }
        int temp = 0;
        StringBuffer sb = new StringBuffer(length);
        char[] ch = str.toCharArray();
        for (char c : ch) {
            sb.append(c);
            if (c > 256) {
                temp += 2;
            } else {
                temp += 1;
            }
            if (temp >= length) {
                if (dot != null) {
                    sb.append(dot);
                }
                break;
            }
        }
        return sb.toString();
    }

    /**
     * 描述:截取字符串从第一个指定字符.
     *
     * @param str1   原文本
     * @param str2   指定字符
     * @param offset 偏移的索引
     * @return 截取后的字符串
     */
    public static String cutStringFromChar(String str1, String str2, int offset) {
        if (isEmpty(str1)) {
            return "";
        }
        int start = str1.indexOf(str2);
        if (start != -1) {
            if (str1.length() > start + offset) {
                return str1.substring(start + offset);
            }
        }
        return "";
    }

    /**
     * 描述:获取字节长度.
     *
     * @param str     文本
     * @param charset 字符集(GBK)
     * @return the int
     */
    public static int strlen(String str, String charset) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        int length = 0;
        try {
            length = str.getBytes(charset).length;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }

    /**
     * 获取大小的描述.
     *
     * @param size 字节个数
     * @return 大小的描述
     */
    public static String getSizeDesc(long size) {
        String suffix = "B";
        if (size >= 1024) {
            suffix = "K";
            size = size >> 10;
            if (size >= 1024) {
                suffix = "M";
                //size /= 1024;
                size = size >> 10;
                if (size >= 1024) {
                    suffix = "G";
                    size = size >> 10;
                    //size /= 1024;
                }
            }
        }
        return size + suffix;
    }

    /**
     * 描述:ip地址转换为10进制数.
     *
     * @param ip the ip
     * @return the long
     */
    public static long ip2int(String ip) {
        ip = ip.replace(".", ",");
        String[] items = ip.split(",");
        return Long.valueOf(items[0]) << 24 | Long.valueOf(items[1]) << 16 | Long.valueOf(items[2]) << 8 | Long.valueOf(items[3]);
    }

    /**
     * 字符串 千位符  保留两位小数点后两位
     *
     * @param num
     * @return
     */
    public static String num2thousand00(String num) {
        if (!isNumeric(num)) {
            return num;
        }

        String numStr = "";
        if (isEmpty(num)) {
            return numStr;
        }
        DecimalFormat df = new DecimalFormat("#,##0.00");
        numStr = df.format(new BigDecimal(num));
        return numStr;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            try {
                Double.parseDouble(str);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值