All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.kit.StringKit Maven / Gradle / Ivy

There is a newer version: 2.3.8.RELEASE
Show newest version
package com.feingto.cloud.kit;

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串转换工具
 *
 * @author longfei
 */
@Slf4j
@SuppressWarnings("unused")
public class StringKit {
    /**
     * 逗号分割字符串
     *
     * @param str String 原始字符串
     * @return String[] 分割后的字符串数组
     */
    public static String[] split(String str) {
        return split(str, ",");
    }

    /**
     * 分割字符串
     *
     * @param str       String 原始字符串
     * @param splitsign String 分隔符
     * @return String[] 分割后的字符串数组
     */
    public static String[] split(String str, String splitsign) {
        int index;
        if (str == null || splitsign == null) {
            return null;
        }
        ArrayList al = new ArrayList<>();
        while ((index = str.indexOf(splitsign)) != -1) {
            al.add(str.substring(0, index));
            str = str.substring(index + splitsign.length());
        }
        al.add(str);
        return al.toArray(new String[0]);
    }

    /**
     * 替换字符串
     *
     * @param from   String 原始字符串
     * @param to     String 目标字符串
     * @param source String 母字符串
     * @return String 替换后的字符串
     */
    public static String replace(String from, String to, String source) {
        if (source == null || from == null || to == null)
            return null;
        StringBuilder str = new StringBuilder("");
        int index;
        while ((index = source.indexOf(from)) != -1) {
            str.append(source.substring(0, index)).append(to);
            source = source.substring(index + from.length());
        }
        str.append(source);
        return str.toString();
    }

    /**
     * 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号)
     *
     * @param str String 原始字符串
     * @return String 替换后的字符串
     */
    public static String htmlencode(String str) {
        return str == null ? null : replace("\"", """, replace("<", "<", str));
    }

    /**
     * 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)
     *
     * @param str String
     * @return String
     */
    public static String htmldecode(String str) {
        return str == null ? null : replace(""", "\"", replace("<", "<", str));
    }

    /**
     * 在页面上直接显示文本内容,替换小于号,空格,回车,TAB
     *
     * @param str String 原始字符串
     * @return String 替换后的字符串
     */
    public static String htmlshow(String str) {
        if (str == null) {
            return null;
        } else {
            str = replace("<", "<", str);
            str = replace(" ", " ", str);
            str = replace("\r\n", "
", str); str = replace("\n", "
", str); str = replace("\t", "    ", str); return str; } } public static String htmlToText(String str) { String regEx_script = "]*?>[\\s\\S]*?<\\/script>"; String regEx_style = "]*?>[\\s\\S]*?<\\/style>"; String regEx_html = "<[^>]+>"; String regEx_space = "\\s*|\t|\r|\n"; Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(str); str = m_script.replaceAll(""); Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(str); str = m_style.replaceAll(""); Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(str); str = m_html.replaceAll(""); Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE); Matcher m_space = p_space.matcher(str); str = m_space.replaceAll(""); return str.trim(); } public static boolean isBlank(String str) { return str == null || str.trim().length() == 0; } public static boolean isNotBlank(String str) { return str != null && str.trim().length() > 0; } public static boolean isEmpty(String str) { return str == null || str.length() == 0; } public static boolean isNotEmpty(String str) { return str != null && str.length() > 0; } /** * 人民币转成大写 * * @param str 数字字符串 * @return String 人民币转换成大写后的字符串 */ public static String hangeToBig(String str) { double value; try { value = Double.parseDouble(str.trim()); } catch (Exception e) { return null; } char[] hunit = {'拾', '佰', '仟'};// 段内位置表示 char[] vunit = {'万', '亿'}; // 段名表示 char[] digit = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'}; // 数字表示 long midVal = (long) (value * 100);// 转化成整形 String valStr = String.valueOf(midVal);// 转化成字符串 String head = valStr.substring(0, valStr.length() - 2);// 取整数部分 String rail = valStr.substring(valStr.length() - 2);// 取小数部分 StringBuilder prefix = new StringBuilder();// 整数部分转化的结果 String suffix;// 小数部分转化的结果 // 处理小数点后面的数 if (rail.equals("00")) {// 如果小数部分为0 suffix = "整"; } else { suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分";// 否则把角分转化出来 } // 处理小数点前面的数 char[] chDig = head.toCharArray();// 把整数部分转化成字符数组 char zero = '0';// 标志'0'表示出现过0 byte zeroSerNum = 0;// 连续出现0的次数 for (int i = 0; i < chDig.length; i++) {// 循环处理每个数字 int idx = (chDig.length - i - 1) % 4;// 取段内位置 int vidx = (chDig.length - i - 1) / 4;// 取段位置 if (chDig[i] == '0') {// 如果当前字符是0 zeroSerNum++;// 连续0次数递增 if (zero == '0') {// 标志 zero = digit[0]; } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) { prefix.append(vunit[vidx - 1]); zero = '0'; } continue; } zeroSerNum = 0;// 连续0次数清零 if (zero != '0') {// 如果标志不为0,则加上,例如万,亿什么的 prefix.append(zero); zero = '0'; } prefix.append(digit[chDig[i] - '0']);// 转化该数字表示 if (idx > 0) prefix.append(hunit[idx - 1]); if (idx == 0 && vidx > 0) { prefix.append(vunit[vidx - 1]);// 段结束位置应该加上段名如万,亿 } } if (prefix.length() > 0) prefix.append('圆');// 如果整数部分存在,则有圆的字样 return prefix + suffix;// 返回正确表示 } /** * 去掉字符串中重复的子字符串 * * @param str 原字符串,如果有子字符串则用空格隔开以表示子字符串 * @return String 返回去掉重复子字符串后的字符串 */ public static String removeSameString(String str) { Set mLinkedSet = new LinkedHashSet<>();// set集合的特征:其子集不可以重复 String[] strArray = str.split(" ");// 根据空格(正则表达式)分割字符串 StringBuilder sb = new StringBuilder(); for (String aStrArray : strArray) { if (!mLinkedSet.contains(aStrArray)) { mLinkedSet.add(aStrArray); sb.append(aStrArray).append(" "); } } return sb.toString(); } /** * 过滤特殊字符 * * @param src 需要过滤的字符串 */ public static String encoding(String src) { if (src == null) return ""; StringBuilder result = new StringBuilder(); src = src.trim(); for (int pos = 0; pos < src.length(); pos++) { switch (src.charAt(pos)) { case '\"': result.append("""); break; case '<': result.append("<"); break; case '>': result.append(">"); break; case '\'': result.append("'"); break; case '&': result.append("&"); break; case '%': result.append("&pc;"); break; case '_': result.append("&ul;"); break; case '#': result.append("&shap;"); break; case '?': result.append("&ques;"); break; default: result.append(src.charAt(pos)); break; } } return result.toString(); } /** * 反过滤特殊字符 * * @param src 需要反过滤的字符串 */ public static String decoding(String src) { if (src == null) return ""; String result = src; result = result.replace(""", "\"").replace("'", "\'"); result = result.replace("<", "<").replace(">", ">"); result = result.replace("&", "&"); result = result.replace("&pc;", "%").replace("&ul", "_"); result = result.replace("&shap;", "#").replace("&ques", "?"); return result; } /** * 数组转换成String, 默认分隔符为, * * @param objects 数组 */ public static String toString(Object[] objects) { if (objects == null) return null; if (objects.length == 0) return ""; StringBuilder sb = new StringBuilder(); for (Object obj : objects) { sb.append(',').append(ObjectKit.toString(obj)); } return sb.substring(1); } /** * 数组转换成String * * @param objects 数组 * @param splitStr 分隔符 */ public static String toString(Object[] objects, String splitStr) { if (objects == null) return null; if (objects.length == 0) return ""; StringBuilder sb = new StringBuilder(); for (Object obj : objects) { sb.append(splitStr).append(ObjectKit.toString(obj)); } return sb.substring(1); } /** * 集合转换成String, 默认分隔符为, * * @param coll 集合 */ public static String toString(Collection coll) { return toString(coll, ","); } /** * 集合转换成String * * @param coll 集合 * @param splitStr 分隔符 */ public static String toString(Collection coll, String splitStr) { if (coll == null) { return null; } else if (coll.size() == 0) { return ""; } else { StringBuilder sb = new StringBuilder(); for (Object object : coll) { sb.append(splitStr).append(object.toString()); } return sb.substring(1); } } public static String toQuoteString(Collection coll) { if (coll == null) { return null; } else if (coll.size() == 0) { return ""; } else { StringBuilder sb = new StringBuilder(); for (Object object : coll) { sb.append(",").append("\"").append(object.toString()).append("\""); } return sb.substring(1); } } /** * 是否包含某个字符串 * * @param strs 字符串数组 * @param str 包含的字符串 */ public static boolean hasStr(String[] strs, String str) { if (strs != null && str != null) { for (String s : strs) { if (str.equals(s)) { return true; } } } return false; } /** * 快捷替换 * 举例: * 源字符串 "insert into {0} values({1},{2})" * 传入参数为 test、id、name * 替换后的字符串为 "insert into test value(id,name)" * * @param str 源字符串 * @param args 参数 * @return 替换后的字符串 */ public static String replaceRegex(String str, Object... args) { if (args == null) return str; for (int i = 0; i < args.length; i++) { String arg = args[i].toString(); str = str.replace("{" + i + "}", arg); } return str; } public static String null2String(Object str) { return str == null ? "" : str.toString(); } public static String firstUpperCase(String str) { return str != null && !isEmpty(str) ? (str.length() == 1 ? str.toUpperCase() : str.substring(0, 1).toUpperCase() + str.substring(1)) : ""; } public static String firstLowerCase(String str) { return str != null && !isEmpty(str) ? (str.length() == 1 ? str.toLowerCase() : str.substring(0, 1).toLowerCase() + str.substring(1)) : ""; } public static String append(String... strings) { StringBuilder sb = new StringBuilder(); for (String s : strings) { sb.append(s); } return sb.toString(); } public static String at(String str, int pos) { return pos >= str.length() ? null : str.substring(pos, pos + 1); } public static String getSuffix(String str) { int idx = str.lastIndexOf("."); return idx < 0 ? "" : str.substring(str.lastIndexOf(".")); } /** * 按行读取字符串转换为Set集合 * * @param str 源字符串 * @return Set集合 */ public static Set readerLine(String str) { Set strings = Sets.newHashSet(); if (StringUtils.hasText(str)) { LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(str)); String line; try { while ((line = lineNumberReader.readLine()) != null) { strings.add(line); } } catch (IOException e) { log.error("IOException while parsing string: " + str, e); } } return strings; } /** * 从字符串中提取数字 * * @param str 源字符串 * @return 数字字符串 */ public static String stringNum(String str) { String regEx = "[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy